Java Code Documentation

UserInputOnMapController

Full name: jfreerails.client.top.UserInputOnMapController

Documentation

/**
* Handles key presses and mouse movements on the map - responsible for moving
* the cursor etc.
*
* @author Luke
*/

Source Code

/**
* Handles key presses and mouse movements on the map - responsible for moving
* the cursor etc.
*
* @author Luke
*/
public class UserInputOnMapController extends KeyAdapter {
private static final String JFREERAILS_CLIENT_SOUNDS_BUILDTRACK_WAV = "/jfreerails/client/sounds/buildtrack.wav";
private static final Logger logger = Logger
.getLogger(UserInputOnMapController.class.getName());
private StationTypesPopup stationTypesPopup;
private BuildIndustryJPopupMenu buildIndustryJPopupMenu = new BuildIndustryJPopupMenu();
private MapViewJComponent mapView;
private TrackMoveProducer trackBuilder;
private DialogueBoxController dialogueBoxController;
private final ModelRoot modelRoot;
private final ActionRoot actionRoot;
private final MouseInputAdapter mouseInputAdapter = new CursorMouseAdapter();
/**
* Used to determine if mouse clicks are on trains.
*/
private TrainRenderer trainRenderer;
private BuildTrackController buildTrack;
private SoundManager soundManager = SoundManager.getSoundManager();
private boolean ignoreDragging = false;
public UserInputOnMapController(ModelRoot mr, ActionRoot ar) {
modelRoot = mr;
actionRoot = ar;
}
private class CursorMouseAdapter extends MouseInputAdapter {
private boolean pressedInside = false;
@Override
public void mouseClicked(MouseEvent evt) {
boolean isDoubleClick = evt.getClickCount() == 2;
ReadOnlyWorld w = modelRoot.getWorld();
FreerailsPrincipal principal = modelRoot.getPrincipal();
if (SwingUtilities.isLeftMouseButton(evt)) {
int x = evt.getX();
int y = evt.getY();
Double time = (Double) modelRoot.getProperty(Property.TIME);
int clickedTrain = -1;
//Iterate in reverse order since later trains are rendered over earlier ones.
for (int i = w.size(principal, KEY.TRAINS) -1; i >= 0 ; i--) {
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS, i);
TrainAccessor ta = new TrainAccessor(w, principal, i);
TrainPositionOnMap pos = ta.findPosition(time);
List<Map.Entry<Point, Step>> positions = trainRenderer.calcPositions(train, pos);
boolean hit = trainRenderer.isHit(evt.getPoint(), train, positions);
if(hit){
clickedTrain = i;
break;
}
}
if (clickedTrain != -1) {
modelRoot.setProperty(Property.SELECTED_TRAIN, clickedTrain);
if (isDoubleClick) {
dialogueBoxController.showTrainOrders(clickedTrain);
}
} else {
if (isDoubleClick) {
ImPoint cursorPosition = (ImPoint) modelRoot.getProperty(Property.CURSOR_POSITION);
dialogueBoxController.showStationOrTerrainInfo(cursorPosition.x,
cursorPosition.y);
}
}
}
}
@Override
public void mousePressed(MouseEvent evt
) {
if (SwingUtilities.isLeftMouseButton(evt)) {
ignoreDragging = false;
int x = evt.getX();
int y = evt.getY();
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
// only jump - no track building
moveCursorJump(new ImPoint(x / tileSize.width, y
/ tileSize.height));
mapView.requestFocus();
pressedInside = true;
/*
* Fix for bug [ 972866 ] Build track by dragging - only when
* build track selected
*/
boolean isBuildTrackModeSet = trackBuilder
.getTrackBuilderMode() == BUILD_TRACK;
if (isBuildTrackModeSet) {
buildTrack.show();
}
} else if (SwingUtilities.isRightMouseButton(evt)) {
// Cancel building track.
buildTrack.hide();
ignoreDragging = true;
setIgnoreKeyEvents(false);
}
}
@Override
public void mouseDragged(MouseEvent evt
) {
BuildMode trackBuilderMode = trackBuilder.getTrackBuilderMode();
/*
* Fix for bug [ 972866 ] Build track by dragging - only when build
* track selected
* Fix for bug [1537413 ] Exception when building station.
*/
boolean trackBuildingOn = (trackBuilderMode == BUILD_TRACK)
|| (trackBuilderMode == REMOVE_TRACK)
|| (trackBuilderMode == UPGRADE_TRACK);
trackBuildingOn = trackBuildingOn
&& (modelRoot.getProperty(ModelRoot.Property.CURSOR_MODE) == ModelRoot.Value.BUILD_TRACK_CURSOR_MODE);
if (SwingUtilities.isLeftMouseButton(evt) && pressedInside
&& trackBuildingOn && !ignoreDragging) {
setIgnoreKeyEvents(true);
int x = evt.getX();
int y = evt.getY();
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
int tileX = x / tileSize.width;
int tileY = y / tileSize.height;
/*
* See the javadoc for JComponent.setAutoscrolls(boolean
* autoscrolls)
*/
assert mapView.getAutoscrolls();
// Scroll view if necessary.
if (!mapView.getVisibleRect().contains(x, y)) {
/*
* Making the rectangle we scroll to 2 tiles wide and
* centered on x, y means that we scroll at least one tile.
* This stops painfully slow scrolling in full screen mode
* when the mouse cannot be dragged far from the viewport
* since it hits the screen edge.
*/
Rectangle r = new Rectangle(x - tileSize.width, y
- tileSize.height, 2 * tileSize.width,
2 * tileSize.height);
mapView.scrollRectToVisible(r);
}
ImPoint to = new ImPoint(
tileX, tileY);
buildTrack.setProposedTrack(to, trackBuilder);
mapView.requestFocus();
}
}
@Override
public void mouseReleased(MouseEvent evt
) {
if (SwingUtilities.isLeftMouseButton(evt)) {
ignoreDragging = false;
setIgnoreKeyEvents(false);
// build a railroad from x,y to current cursor position
if (pressedInside && buildTrack.isBuilding()
&& buildTrack.isBuildTrackSuccessful()) {
// Fix for bug [ 997088 ]
// Is current posisition different from original position?
int x = evt.getX();
int y = evt.getY();
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
int tileX = x / tileSize.width;
int tileY = y / tileSize.height;
if (getCursorPosition().x != tileX
|| getCursorPosition().y != tileY) {
// copy WorldDifferences from buildTrack to World
ImPoint newPosition = buildTrack
.updateWorld(trackBuilder);
setCursorPosition(newPosition);
}
}
pressedInside = false;
buildTrack.hide();
}
}
}
private void cursorOneTileMove(ImPoint oldPosition, Step vector) {
boolean b = (modelRoot.getProperty(ModelRoot.Property.CURSOR_MODE) == ModelRoot.Value.BUILD_TRACK_CURSOR_MODE);
if (null != trackBuilder && b) {
trackBuilder.setBuildTrackStrategy(getBts());
MoveStatus ms = trackBuilder.buildTrack(oldPosition, vector);
if (ms.ok) {
setCursorMessage("");
playAppropriateSound();
} else {
setCursorMessage(ms.message);
}
} else {
logger.warning("No track builder available!");
}
}
private void playAppropriateSound() {
switch (trackBuilder.getTrackBuilderMode()) {
case BUILD_TRACK:
case UPGRADE_TRACK:
soundManager.playSound(JFREERAILS_CLIENT_SOUNDS_BUILDTRACK_WAV, 0);
break;
case REMOVE_TRACK:
soundManager.playSound("/jfreerails/client/sounds/removetrack.wav",
0);
break;
default:
// do nothing
}
}
public void setup(MapViewJComponent mv, TrackMoveProducer trackBuilder,
StationTypesPopup stPopup, ModelRoot mr, DialogueBoxController dbc,
FreerailsCursor cursor, BuildTrackController buildTrack, TrainRenderer trainRenderer) {
this.dialogueBoxController = dbc;
this.mapView = mv;
this.stationTypesPopup = stPopup;
this.trackBuilder = trackBuilder;
this.buildTrack = buildTrack;
this.trainRenderer = trainRenderer;
buildIndustryJPopupMenu.setup(mr, null, null);
/*
* We attempt to remove listeners before adding them to prevent them
* being added several times.
*/
mapView.removeMouseListener(mouseInputAdapter);
mapView.addMouseListener(mouseInputAdapter);
mapView.removeMouseMotionListener(mouseInputAdapter);
mapView.addMouseMotionListener(mouseInputAdapter);
mapView.removeKeyListener(this);
mapView.addKeyListener(this);
}
private void cursorJumped(ImPoint to) {
// if (trackBuilder.getTrackBuilderMode() ==
// TrackMoveProducer.UPGRADE_TRACK) {
// MoveStatus ms = trackBuilder.upgradeTrack(to);
//
// if (ms.ok) {
// setCursorMessage("");
// playAppropriateSound();
// } else {
// setCursorMessage(ms.message);
// }
// }
}
private ImPoint getCursorPosition() {
ImPoint point = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.CURSOR_POSITION);
// Check for null
point = null == point ? new ImPoint() : point;
return point;
}
private void setCursorPosition(ImPoint p) {
// Make a defensive copy.
ImPoint point = p;
modelRoot.setProperty(Property.CURSOR_POSITION, point);
}
private void setCursorMessage(String s) {
modelRoot.setProperty(Property.CURSOR_MESSAGE, s);
}
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (isIgnoreKeyEvents()) {
if (keyCode == KeyEvent.VK_ESCAPE) {
setIgnoreKeyEvents(false);
} else {
return;
}
}
ImPoint cursorPosition = getCursorPosition();
switch (keyCode) {
case KeyEvent.VK_NUMPAD1:
moveCursorOneTile(Step.SOUTH_WEST);
break;
case KeyEvent.VK_NUMPAD2:
moveCursorOneTile(Step.SOUTH);
break;
// @SonnyZ
case KeyEvent.VK_DOWN:
if (e.getModifiers() == 2) {
moveCursorOneTile(Step.SOUTH);
}
break;
// --
case KeyEvent.VK_NUMPAD3:
moveCursorOneTile(Step.SOUTH_EAST);
break;
case KeyEvent.VK_NUMPAD4:
moveCursorOneTile(Step.WEST);
break;
// @SonnyZ
case KeyEvent.VK_LEFT:
if (e.getModifiers() == 2) {
moveCursorOneTile(Step.WEST);
}
break;
// --
case KeyEvent.VK_NUMPAD6:
moveCursorOneTile(Step.EAST);
break;
// @SonnyZ
case KeyEvent.VK_RIGHT:
if (e.getModifiers() == 2) {
moveCursorOneTile(Step.EAST);
}
break;
// --
case KeyEvent.VK_NUMPAD7:
moveCursorOneTile(Step.NORTH_WEST);
break;
case KeyEvent.VK_NUMPAD8:
moveCursorOneTile(Step.NORTH);
break;
// @SonnyZ
case KeyEvent.VK_UP:
if (e.getModifiers() == 2) {
moveCursorOneTile(Step.NORTH);
}
break;
// --
case KeyEvent.VK_NUMPAD9:
moveCursorOneTile(Step.NORTH_EAST);
break;
case KeyEvent.VK_F8: {
// Check whether we can built a station here before proceeding.
if (stationTypesPopup.canBuiltStationHere(cursorPosition.toPoint())) {
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
int x = cursorPosition.x * tileSize.width;
int y = cursorPosition.y * tileSize.height;
stationTypesPopup.showMenu(mapView, x, y, cursorPosition
.toPoint());
} else {
modelRoot.setProperty(Property.QUICK_MESSAGE, "Can't"
+ " build station here!");
}
break;
}
case KeyEvent.VK_BACK_SPACE:
logger.info("Undo building track currently not implemented.");
//
// MoveStatus ms = trackBuilder.undoLastTrackMove();
//
// if (!ms.isOk()) {
// setCursorMessage(ms.message);
// }
break;
case KeyEvent.VK_I: {
dialogueBoxController.showStationOrTerrainInfo(cursorPosition.x,
cursorPosition.y);
break;
}
case KeyEvent.VK_C: {
mapView.centerOnTile(cursorPosition.toPoint());
break;
}
case KeyEvent.VK_B: {
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
int x = cursorPosition.x * tileSize.width;
int y = cursorPosition.y * tileSize.height;
buildIndustryJPopupMenu.setCursorLocation(cursorPosition.toPoint());
buildIndustryJPopupMenu.show(mapView, x, y);
break;
}
case KeyEvent.VK_ESCAPE: {
cancelProposedBuild();
break;
}
// @author SonnyZ
case KeyEvent.VK_X: {
// modelRoot.setProperty(Property.QUICK_MESSAGE, keyCode + " was
// pressed!");
dialogueBoxController.showExitDialog();
break;
}
// @SonnyZ
case KeyEvent.VK_S: {
if (e.getModifiers() == 2) {
ServerControlModel cont = actionRoot.getServerControls();
// String name = JOptionPane.showInputDialog(null, "Saved Game
// Name:","Save
// Game",JOptionPane.QUESTION_MESSAGE,null,null,modelRoot.getPrincipal().getName()).toString();
// modelRoot.setProperty(Property.QUICK_MESSAGE, name);
cont.getSaveGameAction().actionPerformed(null);
}
break;
}
// @SonnyZ
case KeyEvent.VK_L: {
if (e.getModifiers() == 2) {
ServerControlModel cont = actionRoot.getServerControls();
cont.getLoadGameAction().actionPerformed(null);
}
break;
}
// @SonnyZ
case KeyEvent.VK_M: {
// if the screen is not clicked after the broker screen is closed
// and 'M' is pressed
// again, the broker screen will never show up again.
dialogueBoxController.showBrokerScreen();
break;
}
case KeyEvent.VK_F12: {
System.out.println("Disable keyboard input!");
setIgnoreKeyEvents(true);
break;
}
}
}
private void cancelProposedBuild() {
ignoreDragging = true;
buildTrack.hide();
StationBuildModel sbm = actionRoot.getStationBuildModel();
sbm.getStationCancelAction().actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""));
setIgnoreKeyEvents(false);
}
private void moveCursorJump(ImPoint tryThisPoint) {
setCursorMessage("");
if (legalRectangleContains(tryThisPoint)) {
setCursorPosition(tryThisPoint);
cursorJumped(tryThisPoint);
} else {
this.setCursorMessage("Illegal cursor position!");
}
}
/**
* Checks whether specified point is in legal rectangle.
*
* @param tryThisPoint ImPoint
* @return boolean
*/
private boolean legalRectangleContains(ImPoint tryThisPoint) {
ReadOnlyWorld world = modelRoot.getWorld();
int width = world.getMapWidth();
int height = world.getMapHeight();
Rectangle legalRectangle = new Rectangle(0, 0, width, height);
return legalRectangle.contains(tryThisPoint.toPoint());
}
private void moveCursorOneTile(Step v) {
setCursorMessage(null);
ImPoint cursorMapPosition = this.getCursorPosition();
ImPoint tryThisPoint = new ImPoint(cursorMapPosition.x + v.getDx(),
cursorMapPosition.y + v.getDy());
/* Move the cursor. */
if (legalRectangleContains(tryThisPoint)) {
setCursorPosition(tryThisPoint);
cursorOneTileMove(cursorMapPosition, v);
} else {
this.setCursorMessage("Illegal cursor position!");
}
}
private BuildTrackStrategy getBts() {
BuildTrackStrategy bts = (BuildTrackStrategy) modelRoot
.getProperty(ModelRoot.Property.BUILD_TRACK_STRATEGY);
if (null == bts) {
throw new NullPointerException();
}
return bts;
}
private void setIgnoreKeyEvents(boolean ignoreKeyEvents) {
modelRoot.setProperty(Property.IGNORE_KEY_EVENTS, Boolean
.valueOf(ignoreKeyEvents));
}
private boolean isIgnoreKeyEvents() {
Boolean b = (Boolean) modelRoot.getProperty(Property.IGNORE_KEY_EVENTS);
return b.booleanValue();
}
}

BuildMenu

Full name: jfreerails.client.top.BuildMenu

Documentation

/**
* The menu that lets you select a track type.
*
* @author Luke Lindsay
*/

Source Code

/**
* The menu that lets you select a track type.
*
* @author Luke Lindsay
*/
final public class BuildMenu extends javax.swing.JMenu {
private static final long serialVersionUID = 3617850859305055542L;
public BuildMenu() {
super();
}
public void setup(ActionRoot actionRoot) {
this.removeAll();
this.setText("Build");
add(actionRoot.getBuildTrainDialogAction());
}
}

Methods

RenderersRootImpl

Full name: jfreerails.client.top.RenderersRootImpl

Documentation

/**
* Implementation of RenderersRoot whose constructor loads graphics and provides
* feed back using a FreerailsProgressMonitor.
*
* @author Luke
*/

Source Code

/**
* Implementation of RenderersRoot whose constructor loads graphics and provides
* feed back using a FreerailsProgressMonitor.
*
* @author Luke
*/
public class RenderersRootImpl implements RenderersRoot {
private static final Logger logger = Logger.getLogger(RenderersRootImpl.class
.getName());
private final TileRendererList tiles;
private final TrackPieceRendererList trackPieceViewList;
private final ImageManager imageManager;
private final ArrayList<TrainImages> wagonImages = new ArrayList<TrainImages>();
private final ArrayList<TrainImages> engineImages = new ArrayList<TrainImages>();
public RenderersRootImpl(ReadOnlyWorld w, FreerailsProgressMonitor pm)
throws IOException {
URL out = RenderersRootImpl.class.getResource("/experimental");
imageManager = new ImageManagerImpl("/jfreerails/client/graphics/", out
.getPath());
tiles = loadNewTileViewList(w, pm);
trackPieceViewList = loadTrackViews(w, pm);
//rr = new OldTrainImages(w, imageManager, pm);
loadTrainImages(w, pm);
preloadSounds(pm);
}
private void loadTrainImages(ReadOnlyWorld w, FreerailsProgressMonitor pm)
throws IOException {
// Setup progress monitor..
final int numberOfWagonTypes = w.size(SKEY.CARGO_TYPES);
final int numberOfEngineTypes = w.size(SKEY.ENGINE_TYPES);
pm.nextStep(numberOfWagonTypes + numberOfEngineTypes);
int progress = 0;
pm.setValue(progress);
//Load wagon images.
for (int i = 0; i < numberOfWagonTypes; i++) {
CargoType cargoType = (CargoType) w.get(SKEY.CARGO_TYPES, i);
String name = cargoType.getName();
TrainImages ti = new TrainImages(imageManager, name);
wagonImages.add(ti);
pm.setValue(++progress);
}
//Load engine images
for (int i = 0; i < numberOfEngineTypes; i++) {
EngineType engineType = (EngineType) w.get(SKEY.ENGINE_TYPES, i);
String engineTypeName = engineType
.getEngineTypeName();
TrainImages ti = new TrainImages(imageManager, engineTypeName);
engineImages.add(ti);
pm.setValue(++progress);
}
}
private void preloadSounds(FreerailsProgressMonitor pm) {
// Pre-load sounds..
String[] soundsFiles = { "/jfreerails/client/sounds/buildtrack.wav",
"/jfreerails/client/sounds/cash.wav",
"/jfreerails/client/sounds/removetrack.wav",
"/jfreerails/client/sounds/whistle.wav" };
pm.nextStep(soundsFiles.length);
SoundManager sm = SoundManager.getSoundManager();
for (int i = 0; i < soundsFiles.length; i++) {
try {
sm.addClip(soundsFiles[i]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pm.setValue(i + 1);
}
}
private TrackPieceRendererList loadTrackViews(ReadOnlyWorld w,
FreerailsProgressMonitor pm) throws IOException {
return new TrackPieceRendererList(w, imageManager, pm);
}
private TileRendererList loadNewTileViewList(ReadOnlyWorld w,
FreerailsProgressMonitor pm) throws IOException {
ArrayList<TileRenderer> tileRenderers = new ArrayList<TileRenderer>();
// Setup progress monitor..
int numberOfTypes = w.size(SKEY.TERRAIN_TYPES);
pm.nextStep(numberOfTypes);
int progress = 0;
pm.setValue(progress);
for (int i = 0; i < numberOfTypes; i++) {
TerrainType t = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
int[] typesTreatedAsTheSame = new int[] { i };
TileRenderer tr = null;
pm.setValue(++progress);
try {
// XXX hack to make rivers flow into ocean and habours & occean
// treat habours as the same type.
TerrainType.Category thisTerrainCategory = t.getCategory();
if (thisTerrainCategory.equals(TerrainType.Category.River)
|| thisTerrainCategory
.equals(TerrainType.Category.Ocean)) {
// Count number of types with category "water"
int count = 0;
for (int j = 0; j < numberOfTypes; j++) {
TerrainType t2 = (TerrainType) w.get(
SKEY.TERRAIN_TYPES, j);
TerrainType.Category terrainCategory = t2.getCategory();
if (terrainCategory.equals(TerrainType.Category.Ocean)
|| terrainCategory.equals(thisTerrainCategory)) {
count++;
}
}
typesTreatedAsTheSame = new int[count];
count = 0;
for (int j = 0; j < numberOfTypes; j++) {
TerrainType t2 = (TerrainType) w.get(
SKEY.TERRAIN_TYPES, j);
TerrainType.Category terrainCategory = t2.getCategory();
if (terrainCategory.equals(TerrainType.Category.Ocean)
|| terrainCategory.equals(thisTerrainCategory)) {
typesTreatedAsTheSame[count] = j;
count++;
}
}
}
tr = new RiverStyleTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io) {
}
try {
tr = new ForestStyleTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io) {
}
try {
tr = new ChequeredTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io) {
}
try {
tr = new StandardTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io) {
// If the image is missing, we generate it.
logger
.warning("No tile renderer for "
+ t.getTerrainTypeName());
String filename = StandardTileRenderer.generateFilename(t
.getTerrainTypeName());
Image image = QuickRGBTileRendererList.createImageFor(t);
imageManager.setImage(filename, image);
// generatedImages.setImage(filename, image);
try {
tr = new StandardTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io2) {
io2.printStackTrace();
throw new IllegalStateException();
}
}
}
// XXXX add special tile renderer for habours
TileRenderer oceanTileRenderer = null;
for (int j = 0; j < numberOfTypes; j++) {
TerrainType t2 = (TerrainType) w.get(SKEY.TERRAIN_TYPES, j);
String terrainName = t2.getTerrainTypeName();
if (terrainName.equalsIgnoreCase("Ocean")) {
oceanTileRenderer = tileRenderers.get(j);
break;
}
}
for (int j = 0; j < numberOfTypes; j++) {
TerrainType t2 = (TerrainType) w.get(SKEY.TERRAIN_TYPES, j);
String terrainName = t2.getTerrainTypeName();
if (terrainName.equalsIgnoreCase("Harbour")) {
TerrainType t = (TerrainType) w.get(SKEY.TERRAIN_TYPES, j);
TileRenderer tr = new SpecialTileRenderer(imageManager,
new int[] { j }, t, oceanTileRenderer);
tileRenderers.set(j, tr);
break;
}
}
return new TileRendererListImpl(tileRenderers);
}
public TileRendererList getTileViewList() {
return this.tiles;
}
public TrackPieceRendererList getTrackPieceViewList() {
return this.trackPieceViewList;
}
public boolean validate(ReadOnlyWorld w) {
boolean okSoFar = true;
if (!this.tiles.validate(w)) {
okSoFar = false;
}
if (!this.trackPieceViewList.validate(w)) {
okSoFar = false;
}
return okSoFar;
}
// public OldTrainImages getTrainImages() {
// return rr;
// }
public ImageManager getImageManager() {
return imageManager;
}
public Image getImage(String relativeFilename) throws IOException {
return imageManager.getImage(relativeFilename);
}
public TileRenderer getTileViewWithNumber(int i) {
return tiles.getTileViewWithNumber(i);
}
public TrackPieceRenderer getTrackPieceView(int i) {
return trackPieceViewList.getTrackPieceView(i);
}
public TrainImages getWagonImages(int type) {
return wagonImages.get(type);
}
public TrainImages getEngineImages(int type) {
return engineImages.get(type);
}
public Image getScaledImage(String relativeFilename, int height) throws IOException {
return imageManager.getScaledImage(relativeFilename, height);
}
}

SynchronizedEventQueue

Full name: jfreerails.client.top.SynchronizedEventQueue

Documentation

/**
* This event queue is synchronized on the MUTEX. This lets one control when
* events can be dispatched.
*
* Note, changed to be a singleton to get it working on pre 1.4.2 VMs.
*
* @author Luke
*
*/

Source Code

/**
* This event queue is synchronized on the MUTEX. This lets one control when
* events can be dispatched.
*
* Note, changed to be a singleton to get it working on pre 1.4.2 VMs.
*
* @author Luke
*
*/
final public class SynchronizedEventQueue extends EventQueue {
public static final Object MUTEX = new Object();
private static final SynchronizedEventQueue instance = new SynchronizedEventQueue();
private static boolean alreadyInUse = false;
/** Enforce singleton property. */
private SynchronizedEventQueue() {
}
public static synchronized void use() {
if (!alreadyInUse) {
/* set up the synchronized event queue */
EventQueue eventQueue = Toolkit.getDefaultToolkit()
.getSystemEventQueue();
eventQueue.push(instance);
alreadyInUse = true;
}
}
@Override
protected void dispatchEvent(AWTEvent aEvent) {
synchronized (MUTEX) {
try {
super.dispatchEvent(aEvent);
} catch (Exception e) {
/*
* If something goes wrong, lets kill the game straight away to
* avoid hard-to-track-down bugs.
*/
ReportBugTextGenerator.unexpectedException(e);
}
}
}
public static SynchronizedEventQueue getInstance() {
return instance;
}
}

QuickRGBTileRendererList

Full name: jfreerails.client.top.QuickRGBTileRendererList

Documentation

/**
* Simple implementation of TileRendererList, for testing purposes only.
*
* @author Luke
*
*/

Source Code

/**
* Simple implementation of TileRendererList, for testing purposes only.
*
* @author Luke
*
*/
public class QuickRGBTileRendererList implements TileRendererList {
private final int[] rgbValues;
private final Image[] images;
private final HashMap<Integer, Integer> rgb2index = new HashMap<Integer, Integer>();
private final SimpleTileRenderer simpleTileRenderer = new SimpleTileRenderer();
private static final java.awt.GraphicsConfiguration defaultConfiguration = java.awt.GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
public QuickRGBTileRendererList(ReadOnlyWorld w) {
int numberOfTerrainTypes = w.size(SKEY.TERRAIN_TYPES);
rgbValues = new int[numberOfTerrainTypes];
images = new Image[numberOfTerrainTypes];
for (int i = 0; i < numberOfTerrainTypes; i++) {
TerrainType t = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
rgbValues[i] = t.getRGB();
images[i] = createImageFor(t);
rgb2index.put(new Integer(t.getRGB()), new Integer(i));
}
}
public static Image createImageFor(TerrainType t) {
Image image = defaultConfiguration.createCompatibleImage(
Constants.TILE_SIZE, Constants.TILE_SIZE);
Color c = new Color(t.getRGB());
Graphics g = image.getGraphics();
g.setColor(c);
g.fillRect(0, 0, Constants.TILE_SIZE, Constants.TILE_SIZE);
g.dispose();
return image;
}
public TileRenderer getTileViewWithNumber(int i) {
throw new UnsupportedOperationException();
}
public TileRenderer getTileViewWithRGBValue(int rgb) {
Integer i = rgb2index.get(new Integer(rgb));
this.simpleTileRenderer.setImage(images[i.intValue()]);
return simpleTileRenderer;
}
public boolean validate(ReadOnlyWorld world) {
return true;
}
class SimpleTileRenderer implements TileRenderer {
Image i;
public SimpleTileRenderer() {
}
public void setImage(Image i) {
this.i = i;
}
public Image getDefaultIcon() {
return i;
}
public void renderTile(Graphics g, int renderX, int renderY, int mapX,
int mapY, ReadOnlyWorld w) {
g.drawImage(i, renderX, renderY, null);
}
public void dumpImages(ImageManager imageManager) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}
}
}

GUIComponentFactoryTestImpl

Full name: jfreerails.client.top.GUIComponentFactoryTestImpl

Documentation

/**
* Implementation of GUIComponentFactory that returns 'blank' components - used
* for testing the layout of ClientJFrame.
*
* @author Luke
*/

Source Code

/**
* Implementation of GUIComponentFactory that returns 'blank' components - used
* for testing the layout of ClientJFrame.
*
* @author Luke
*/
public class GUIComponentFactoryTestImpl implements GUIComponentFactory {
private final JLabel datejLabel;
private final JLabel cashjLabel;
private final JTabbedPane trainsJPanel;
private final JMenu displayMenu;
private final JScrollPane mainMapView;
private final JMenu buildMenu;
private final JMenu gameMenu;
private final JPanel mapOverview;
private final JMenu helpMenu;
private final JLabel messageJLabel;
private final JMenu brokerMenu;
/** Creates a new instance of GUIComponentFactoryTestImpl. */
public GUIComponentFactoryTestImpl() {
JPanel mainmapjPanel;
trainsJPanel = new JTabbedPane();
datejLabel = new JLabel();
mapOverview = new JPanel();
cashjLabel = new JLabel();
mainMapView = new JScrollPane();
mainmapjPanel = new JPanel();
messageJLabel = new JLabel();
gameMenu = new JMenu();
buildMenu = new JMenu();
displayMenu = new JMenu();
helpMenu = new JMenu();
brokerMenu = new JMenu();
trainsJPanel.setBackground(new java.awt.Color(255, 51, 51));
datejLabel.setText("Jun, 1840");
mapOverview.setBackground(new java.awt.Color(0, 204, 255));
mapOverview.setPreferredSize(new java.awt.Dimension(100, 100));
cashjLabel.setText("$100,000");
mainmapjPanel.setBackground(new java.awt.Color(153, 244, 51));
mainMapView.setViewportView(mainmapjPanel);
messageJLabel.setText("message");
}
public JMenu createReportsMenu() {
return new JMenu("Reports");
}
public JMenu createBuildMenu() {
return buildMenu;
}
public JLabel createCashJLabel() {
return cashjLabel;
}
public JLabel createDateJLabel() {
return datejLabel;
}
public JMenu createDisplayMenu() {
return displayMenu;
}
public JMenu createGameMenu() {
return gameMenu;
}
public JMenu createHelpMenu() {
return helpMenu;
}
public JScrollPane createMainMap() {
return mainMapView;
}
public JPanel createOverviewMap() {
return mapOverview;
}
public JTabbedPane createTrainsJTabPane() {
return trainsJPanel;
}
public JMenu createBrokerMenu() {
return brokerMenu;
}
}

ClientJFrame

Full name: jfreerails.client.top.ClientJFrame

Documentation

/**
* The JFrame that you see while you are playing the game.
*
* @author Luke
*/

Source Code

/**
* The JFrame that you see while you are playing the game.
*
* @author Luke
*/
public class ClientJFrame extends javax.swing.JFrame {
private static final long serialVersionUID = 3834868100742265142L;
private GUIComponentFactory gUIComponentFactory;
/** Creates new form ClientJFrame. */
public ClientJFrame(GUIComponentFactory gcf) {
setup(gcf);
}
private void setup(GUIComponentFactory gcf) {
this.gUIComponentFactory = gcf;
initComponents();
gUIComponentFactory.createDateJLabel();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
rhsjPanel = new javax.swing.JPanel();
mapOverview = gUIComponentFactory.createOverviewMap();
trainsJTabPane1 = gUIComponentFactory.createTrainsJTabPane();
lhsjPanel = new javax.swing.JPanel();
mainMapView = gUIComponentFactory.createMainMap();
statusjPanel = new javax.swing.JPanel();
datejLabel = gUIComponentFactory.createDateJLabel();
cashjLabel = gUIComponentFactory.createCashJLabel();
jMenuBar1 = new javax.swing.JMenuBar();
gameMenu = gUIComponentFactory.createGameMenu();
buildMenu = gUIComponentFactory.createBuildMenu();
BrokerMenu1 = gUIComponentFactory.createBrokerMenu();
displayMenu = gUIComponentFactory.createDisplayMenu();
reportsMenu = gUIComponentFactory.createReportsMenu();
helpMenu = gUIComponentFactory.createHelpMenu();
getContentPane().setLayout(new java.awt.GridBagLayout());
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
rhsjPanel.setLayout(new java.awt.GridBagLayout());
rhsjPanel.add(mapOverview, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
rhsjPanel.add(trainsJTabPane1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
getContentPane().add(rhsjPanel, gridBagConstraints);
lhsjPanel.setLayout(new java.awt.GridBagLayout());
mainMapView.setAlignmentX(0.0F);
mainMapView.setAlignmentY(0.0F);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
lhsjPanel.add(mainMapView, gridBagConstraints);
statusjPanel.add(datejLabel);
statusjPanel.add(cashjLabel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
lhsjPanel.add(statusjPanel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(lhsjPanel, gridBagConstraints);
gameMenu.setText("Game");
jMenuBar1.add(gameMenu);
buildMenu.setText("Build");
jMenuBar1.add(buildMenu);
BrokerMenu1.setText("Broker");
jMenuBar1.add(BrokerMenu1);
displayMenu.setText("Display");
jMenuBar1.add(displayMenu);
reportsMenu.setText("Reports");
jMenuBar1.add(reportsMenu);
helpMenu.setText("Help");
jMenuBar1.add(helpMenu);
setJMenuBar(jMenuBar1);
pack();
}// GEN-END:initComponents
/** Exit the Application. */
private void exitForm(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_exitForm
System.exit(0);
}// GEN-LAST:event_exitForm
public static void main(String args[]) {
new ClientJFrame(new GUIComponentFactoryTestImpl()).setVisible(true);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenu BrokerMenu1;
private javax.swing.JMenu buildMenu;
private javax.swing.JLabel cashjLabel;
private javax.swing.JLabel datejLabel;
private javax.swing.JMenu displayMenu;
private javax.swing.JMenu gameMenu;
private javax.swing.JMenu helpMenu;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel lhsjPanel;
private javax.swing.JScrollPane mainMapView;
private javax.swing.JPanel mapOverview;
private javax.swing.JMenu reportsMenu;
private javax.swing.JPanel rhsjPanel;
private javax.swing.JPanel statusjPanel;
private javax.swing.JTabbedPane trainsJTabPane1;
// End of variables declaration//GEN-END:variables
}

GUIComponentFactory

Full name: jfreerails.client.top.GUIComponentFactory

Documentation

/**
* Defines methods that create the GUI components used by the game.
*
* @author Luke
*/

Source Code

/**
* Defines methods that create the GUI components used by the game.
*
* @author Luke
*/
public interface GUIComponentFactory {
JPanel createOverviewMap();
JTabbedPane createTrainsJTabPane();
JScrollPane createMainMap();
JLabel createCashJLabel();
JLabel createDateJLabel();
JMenu createBuildMenu();
JMenu createReportsMenu();
JMenu createGameMenu();
JMenu createDisplayMenu();
JMenu createHelpMenu();
JMenu createBrokerMenu();
}

BuildIndustryJPopupMenu

Full name: jfreerails.client.top.BuildIndustryJPopupMenu

Documentation

/**
* A JPopupMenu that displays the list of industries that can be built. This
* class contains the code that generates and dispatches a ChangeTileMove when
* the player clicks on the menu.
*
* @author Luke
*
*/

Source Code

/**
* A JPopupMenu that displays the list of industries that can be built. This
* class contains the code that generates and dispatches a ChangeTileMove when
* the player clicks on the menu.
*
* @author Luke
*
*/
public class BuildIndustryJPopupMenu extends JPopupMenu implements View {
private static final long serialVersionUID = 3689636912575165749L;
private final Point cursorLocation = new Point();
public void setCursorLocation(Point p) {
cursorLocation.x = p.x;
cursorLocation.y = p.y;
}
public void setup(final ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
this.removeAll();
final NonNullElements it = new NonNullElements(SKEY.TERRAIN_TYPES,
modelRoot.getWorld());
while (it.next()) {
TerrainType type = (TerrainType) it.getElement();
final Money price = type.getBuildCost();
if (null != price) {
JMenuItem item = new JMenuItem(type.getDisplayName() + " "
+ price);
item.addActionListener(new ActionListener() {
private final int terrainType = it.getIndex();
public void actionPerformed(ActionEvent arg0) {
Move m1 = new ChangeTileMove(modelRoot.getWorld(),
cursorLocation, terrainType);
Transaction t = new AddItemTransaction(
Transaction.Category.INDUSTRIES, terrainType,
1, price.changeSign());
Move m2 = new AddTransactionMove(modelRoot
.getPrincipal(), t);
CompositeMove m3 = new CompositeMove(m1, m2);
MoveStatus ms = modelRoot.doMove(m3);
if (!ms.ok) {
modelRoot.setProperty(
ModelRoot.Property.CURSOR_MESSAGE,
ms.message);
}
}
});
add(item);
}
}
}
}

ConfirmExitJPanel

Full name: jfreerails.client.view.ConfirmExitJPanel

Documentation

/**
* JPanel that displays confirmation of exiting, used when the exit menu item is
* selected or x is pressed.
*
* @author SonnyZ
*/

Source Code

/**
* JPanel that displays confirmation of exiting, used when the exit menu item is
* selected or x is pressed.
*
* @author SonnyZ
*/
public class ConfirmExitJPanel extends javax.swing.JPanel implements View {
private static final long serialVersionUID = 3256728398394110517L;
/** Creates new form ConfirmExitJPanel. */
public ConfirmExitJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
confirmExit = new javax.swing.JButton();
closeJButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(240, 140));
jLabel1.setText("Are you sure you want to Exit?");
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
jPanel1.add(jLabel1);
add(jPanel1, new java.awt.GridBagConstraints());
jPanel2.setLayout(new java.awt.GridBagLayout());
confirmExit.setText("Exit");
confirmExit.setContentAreaFilled(false);
confirmExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
confirmExitActionPerformed(evt);
}
});
jPanel2.add(confirmExit, new java.awt.GridBagConstraints());
closeJButton.setText("Cancel");
jPanel2.add(closeJButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.ipadx = 15;
gridBagConstraints.insets = new java.awt.Insets(3, 0, 0, 0);
add(jPanel2, gridBagConstraints);
}// GEN-END:initComponents
private void confirmExitActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_confirmExitActionPerformed
System.exit(0);
}// GEN-LAST:event_confirmExitActionPerformed
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
closeJButton.setAction(closeAction);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton closeJButton;
private javax.swing.JButton confirmExit;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
// End of variables declaration//GEN-END:variables
}

SaveGameJPanel

Full name: jfreerails.client.view.SaveGameJPanel

Documentation

/**
*
* @author Luke
*/

Source Code

/**
*
* @author Luke
*/
public class SaveGameJPanel extends javax.swing.JPanel implements View{
private static final long serialVersionUID = 4031907071040752589L;
/** Creates new form SaveGameJPanel */
public SaveGameJPanel() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jLabel1 = new javax.swing.JLabel();
fileNameTextField = new javax.swing.JTextField();
oKButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
jLabel1.setText("Please enter a name for the save game.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(jLabel1, gridBagConstraints);
fileNameTextField.setText("savegame");
fileNameTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fileNameTextFieldActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(fileNameTextField, gridBagConstraints);
oKButton.setText("OK");
oKButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
oKButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(oKButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(cancelButton, gridBagConstraints);
}
// </editor-fold>//GEN-END:initComponents
private void oKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_oKButtonActionPerformed
String filename = fileNameTextField.getText();
// Save the current game using the string
modelRoot.setProperty(Property.QUICK_MESSAGE, "Saved game "
+ filename);
Message2Server message2 = new SaveGameMessage2Server(1,
filename + ".sav");
modelRoot.sendCommand(message2);
close.actionPerformed(evt);
}//GEN-LAST:event_oKButtonActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
close.actionPerformed(evt);
}//GEN-LAST:event_cancelButtonActionPerformed
private void fileNameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileNameTextFieldActionPerformed
// TODO add your handling code here:
System.out.println("fileNameTextFieldActionPerformed"+evt.toString());
}//GEN-LAST:event_fileNameTextFieldActionPerformed
public void setup(ModelRoot m, RenderersRoot vl,
Action closeAction) {
this.close = closeAction;
this.modelRoot = m;
}
ModelRoot modelRoot;
ActionListener close;
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JButton cancelButton;
javax.swing.JTextField fileNameTextField;
javax.swing.JLabel jLabel1;
javax.swing.JButton oKButton;
// End of variables declaration//GEN-END:variables
}

TrainListJPanel

Full name: jfreerails.client.view.TrainListJPanel

Documentation

/**
* JPanel that displays a list of trains, used for the train list window and the
* train roster tab.
*
* @author Luke
*/

Source Code

/**
* JPanel that displays a list of trains, used for the train list window and the
* train roster tab.
*
* @author Luke
*/
public class TrainListJPanel extends javax.swing.JPanel implements View, ModelRootListener {
private static final long serialVersionUID = 3832905463863064626L;
private ReadOnlyWorld world;
private FreerailsPrincipal principal;
private int lastNumberOfTrains = -1;
private boolean rhsjTabPane = false; // if the train list is for the
// rhsjTabPane then use the original
// renderer, if not use the
// trainsummaryjpanel
/** Creates new form TrainListJPanel. */
public TrainListJPanel() {
initComponents();
}
public TrainListJPanel(boolean isInRHSJTabPane) {
this();
rhsjTabPane = isInRHSJTabPane;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
trainSummaryJPanel1 = new jfreerails.client.view.TrainSummaryJPanel();
closeJButton = new javax.swing.JButton();
showDetails = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
trainNumLabel = new javax.swing.JLabel();
trainHeadingLabel = new javax.swing.JLabel();
maintenanceLabel = new javax.swing.JLabel();
incomeLabel = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(510, 300));
closeJButton.setText("Close");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(closeJButton, gridBagConstraints);
showDetails.setText("Show details");
showDetails.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showDetailsActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(showDetails, gridBagConstraints);
jList1
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.setCellRenderer(trainSummaryJPanel1);
jList1.setDoubleBuffered(true);
jList1.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
jList1KeyPressed(evt);
}
});
jList1
.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(
javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jList1.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
jList1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jList1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
trainNumLabel.setText("Train Number");
trainNumLabel.setMaximumSize(new java.awt.Dimension(500, 500));
trainNumLabel.setPreferredSize(new java.awt.Dimension(100, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
add(trainNumLabel, gridBagConstraints);
trainHeadingLabel.setText("Headed For");
trainHeadingLabel.setPreferredSize(new java.awt.Dimension(100, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
add(trainHeadingLabel, gridBagConstraints);
maintenanceLabel.setText("Maintenance YTD");
maintenanceLabel.setPreferredSize(new java.awt.Dimension(100, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
add(maintenanceLabel, gridBagConstraints);
incomeLabel.setText("Income YTD");
incomeLabel.setPreferredSize(new java.awt.Dimension(100, 14));
add(incomeLabel, new java.awt.GridBagConstraints());
}// GEN-END:initComponents
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {// GEN-FIRST:event_jList1ValueChanged
// if a train is selected, enable the 'show details' button.
if (jList1.getSelectedIndex() != -1) {
this.showDetails.setEnabled(true);
} else {
this.showDetails.setEnabled(false);
}
}// GEN-LAST:event_jList1ValueChanged
private void showDetailsActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showDetailsActionPerformed
showTrainDetails.actionPerformed(evt);
}// GEN-LAST:event_showDetailsActionPerformed
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_jList1MouseClicked
// Add your handling code here:
if (evt.getClickCount() == 2) {
showTrainDetails.actionPerformed(null);
}
}// GEN-LAST:event_jList1MouseClicked
private void jList1KeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_jList1KeyPressed
// Add your handling code here:
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
showTrainDetails.actionPerformed(null);
}
}// GEN-LAST:event_jList1KeyPressed
public void setup(final ModelRoot mr, RenderersRoot vl,
Action closeAction) {
world = mr.getWorld();
trainSummaryJPanel1.setup(mr, vl, null);
if (rhsjTabPane) {
jList1.setModel(new World2ListModelAdapter(mr.getWorld(),
KEY.TRAINS, mr.getPrincipal()));
TrainListCellRenderer trainView = new TrainListCellRenderer(mr, vl);
jList1.setCellRenderer(trainView);
trainView.setHeight(trainViewHeight);
}
ActionListener[] oldListeners = closeJButton.getActionListeners();
for (int i = 0; i < oldListeners.length; i++) {
closeJButton.removeActionListener(oldListeners[i]);
}
closeJButton.addActionListener(closeAction);
ListSelectionListener[] old = jList1.getListSelectionListeners();
for(ListSelectionListener x : old){
jList1.removeListSelectionListener(x);
}
jList1.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int id = getSelectedTrainID();
mr.setProperty(ModelRoot.Property.SELECTED_TRAIN, id);
}
});
principal = mr.getPrincipal();
ModelRootImpl mri = (ModelRootImpl) mr;
mri.addPropertyChangeListener(this);
}
void setShowTrainDetailsActionListener(ActionListener l) {
showTrainDetails = l;
}
private ActionListener showTrainDetails = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
};
int getSelectedTrainID() {
/*
* Note, the selected index is not the train id since trains that have
* been removed are not shown on the list.
*/
int row = jList1.getSelectedIndex();
if (row == -1) {
return -1;
} else {
return NonNullElements.row2index(world, KEY.TRAINS, principal, row);
}
}
/** When the train list is shown on a tab we don't want the buttons. */
void removeButtons() {
this.removeAll();
java.awt.GridBagConstraints gridBagConstraints;
setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton closeJButton;
private javax.swing.JLabel incomeLabel;
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel maintenanceLabel;
private javax.swing.JButton showDetails;
private javax.swing.JLabel trainHeadingLabel;
private javax.swing.JLabel trainNumLabel;
private jfreerails.client.view.TrainSummaryJPanel trainSummaryJPanel1;
// End of variables declaration//GEN-END:variables
private int trainViewHeight = 50;
@Override
public void setVisible(boolean aFlag) {
if (aFlag && null != world) {
// jList1.setModel(new World2ListModelAdapter(world,
// KEY.TRAINS,principal));
}
super.setVisible(aFlag);
}
public void setTrainViewHeight(int trainViewHeight) {
this.trainViewHeight = trainViewHeight;
}
@Override
public void paint(Graphics g) {
if (null != world) {
NonNullElements trains = new NonNullElements(KEY.TRAINS, world,
principal);
int newNumberOfTrains = trains.size();
if (newNumberOfTrains != this.lastNumberOfTrains) {
jList1.setModel(new World2ListModelAdapter(world, KEY.TRAINS,
principal));
if (newNumberOfTrains > 0) {
jList1.setSelectedIndex(0);
}
lastNumberOfTrains = newNumberOfTrains;
}
}
super.paint(g);
}
@Override
public void propertyChange(ModelRoot.Property p, Object oldValue, Object newValue) {
if(ModelRoot.Property.SELECTED_TRAIN == p){
if(!newValue.equals(this.getSelectedTrainID())){
//update needed..
TrainModel train = (TrainModel) world.get(principal, KEY.TRAINS, (int) newValue);
this.jList1.setSelectedValue(train, true);
}
}
}
}

DialogueBoxController

Full name: jfreerails.client.view.DialogueBoxController

Documentation

/**
* This class is responsible for displaying dialogue boxes, adding borders to
* them as appropriate, and returning focus to the last focus owner after a
* dialogue box has been closed. It is also responsible for adding components
* that need to update in response to moves to the MoveChainFork. Currently
* dialogue boxes are not separate windows. Instead, they are drawn on the modal
* layer of the main JFrames LayerPlane. This allows dialogue boxes with
* transparent regions to be used.
*
* @author lindsal8
* @author smackay
*/

Source Code

/**
* This class is responsible for displaying dialogue boxes, adding borders to
* them as appropriate, and returning focus to the last focus owner after a
* dialogue box has been closed. It is also responsible for adding components
* that need to update in response to moves to the MoveChainFork. Currently
* dialogue boxes are not separate windows. Instead, they are drawn on the modal
* layer of the main JFrames LayerPlane. This allows dialogue boxes with
* transparent regions to be used.
*
* @author lindsal8
* @author smackay
*/
public class DialogueBoxController implements WorldListListener {
private static final Logger logger = Logger
.getLogger(DialogueBoxController.class.getName());
private final JButton closeButton = new JButton("Close");
private SelectEngineJPanel selectEngine;
private final MyGlassPanel glassPanel;
private NewsPaperJPanel newspaper;
private SelectWagonsJPanel selectWagons;
private HtmlJPanel showControls;
private HtmlJPanel about;
private HtmlJPanel how2play;
private HtmlJPanel javaProperties;
private TerrainInfoJPanel terrainInfo;
private StationInfoJPanel stationInfo;
private TrainDialogueJPanel trainDialogueJPanel;
private ReadOnlyWorld world;
private ModelRootImpl modelRoot;
private RenderersRoot vl;
private Component defaultFocusOwner = null;
private final JFrame frame;
private JInternalFrame dialogueJInternalFrame;
/**
* Use this Action to close a dialogue without performing any other
* action.
*/
private final Action closeCurrentDialogue = new AbstractAction("Close") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
closeContent();
}
};
private final Action selectEngineAction = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
showSelectWagons();
}
};
private final ActionListener trainDetailsButtonActionListener = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
showTrainList();
}
};
private final Action selectWagonsAction = new AbstractAction("Next") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
WorldIterator wi = new NonNullElements(KEY.STATIONS, modelRoot
.getWorld(), modelRoot.getPrincipal());
if (wi.next()) {
StationModel station = (StationModel) wi.getElement();
ImList<PlannedTrain> before = station.getProduction();
int engineType = selectEngine.getEngineType();
int[] wagonTypes = selectWagons.getWagons();
ImList<PlannedTrain> after = new ImList<PlannedTrain>(
new PlannedTrain(engineType, wagonTypes));
Move m = new ChangeProductionAtEngineShopMove(before, after, wi
.getIndex(), modelRoot.getPrincipal());
modelRoot.doMove(m);
}
closeContent();
}
};
public DialogueBoxController(JFrame frame, ModelRootImpl mr) {
this.frame = frame;
modelRoot = mr;
// Setup glass panel..
glassPanel = new MyGlassPanel();
glassPanel.setSize(frame.getSize());
frame.getLayeredPane().add(glassPanel, JLayeredPane.MODAL_LAYER);
glassPanel.revalidate();
glassPanel.setVisible(false);
// We need to resize the glass panel when its parent resizes.
frame.getLayeredPane().addComponentListener(
new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(
java.awt.event.ComponentEvent evt) {
glassPanel.setSize(glassPanel.getParent().getSize());
glassPanel.revalidate();
}
});
closeButton.addActionListener(closeCurrentDialogue);
showControls = new HtmlJPanel(DialogueBoxController.class
.getResource("/jfreerails/client/view/game_controls.html"));
about = new HtmlJPanel(DialogueBoxController.class
.getResource("/jfreerails/client/view/about.htm"));
how2play = new HtmlJPanel(DialogueBoxController.class
.getResource("/jfreerails/client/view/how_to_play.htm"));
terrainInfo = new TerrainInfoJPanel();
stationInfo = new StationInfoJPanel();
javaProperties = new HtmlJPanel(ShowJavaProperties
.getPropertiesHtmlString());
Dimension d = javaProperties.getPreferredSize();
d.width += 50;
javaProperties.setPreferredSize(d);
newspaper = new NewsPaperJPanel();
selectWagons = new SelectWagonsJPanel();
selectEngine = new SelectEngineJPanel();
trainDialogueJPanel = new TrainDialogueJPanel();
}
/**
* Called when a new game is started or a game is loaded.
* <p>
* <b>Be extremely careful with the references of objects allocated in this
* method to avoid memory leaks - see bug 967677 (OutOfMemoryError after
* starting several new games). </b>
* </p>
*/
public void setup(ModelRootImpl mr, RenderersRoot vl) {
this.modelRoot = mr;
this.vl = vl;
modelRoot.addListListener(this); // When a new train gets built, we
// show the train info etc
this.world = modelRoot.getWorld();
if (world == null)
throw new NullPointerException();
if (vl == null)
throw new NullPointerException();
// Setup the various dialogue boxes.
// setup the terrain info dialogue.
terrainInfo.setup(world, vl);
// setup the supply and demand at station dialogue.
stationInfo.setup(modelRoot, vl, this.closeCurrentDialogue);
modelRoot.addListListener(stationInfo);
// setup the 'show controls' dialogue
showControls.setup(this.modelRoot, vl, this.closeCurrentDialogue);
about.setup(this.modelRoot, vl, this.closeCurrentDialogue);
how2play.setup(this.modelRoot, vl, this.closeCurrentDialogue);
javaProperties.setup(this.modelRoot, vl, this.closeCurrentDialogue);
// Set up train orders dialogue
// trainScheduleJPanel = new TrainScheduleJPanel();
// trainScheduleJPanel.setup(w, vl);
// moveChainFork.add(trainScheduleJPanel);
// Set up select engine dialogue.
selectEngine.setCancelButtonActionListener(this.closeCurrentDialogue);
selectEngine.setup(modelRoot, vl, selectEngineAction);
newspaper.setup(modelRoot, vl, closeCurrentDialogue);
selectWagons.setup(modelRoot, vl, selectWagonsAction);
trainDialogueJPanel.setup(modelRoot, vl, this.closeCurrentDialogue);
modelRoot.addListListener(trainDialogueJPanel);
trainDialogueJPanel
.setTrainDetailsButtonActionListener(trainDetailsButtonActionListener);
trainDialogueJPanel
.setCancelButtonActionListener(this.closeCurrentDialogue);
}
public void showSaveGame(){
SaveGameJPanel saveGameJPanel = new SaveGameJPanel();
saveGameJPanel.setup(modelRoot, vl, this.closeCurrentDialogue);
showContent(saveGameJPanel);
}
public void showSelectSavedGame2Load(){
Message2Server refreshGames = new RefreshListOfGamesMessage2Server(2);
modelRoot.sendCommand(refreshGames);
LoadGameJPanel loadGameJPane = new LoadGameJPanel();
loadGameJPane.setup(modelRoot, vl, this.closeCurrentDialogue);
showContent(loadGameJPane);
}
public void showTrainOrders() {
WorldIterator wi = new NonNullElements(KEY.TRAINS, world, modelRoot
.getPrincipal());
if (!wi.next()) {
modelRoot.setProperty(Property.QUICK_MESSAGE, "Cannot"
+ " show train orders since there are no" + " trains!");
} else {
trainDialogueJPanel.display(wi.getIndex());
this.showContent(trainDialogueJPanel);
}
}
public void showSelectEngine() {
WorldIterator wi = new NonNullElements(KEY.STATIONS, world, modelRoot
.getPrincipal());
if (!wi.next()) {
modelRoot.setProperty(Property.QUICK_MESSAGE, "Can't"
+ " build train since there are no stations");
} else {
showContent(selectEngine);
}
}
public void showGameControls() {
showContent(this.showControls);
}
public void showIncomeStatement() {
IncomeStatementHtmlJPanel bs = new IncomeStatementHtmlJPanel();
bs.setup(this.modelRoot, vl, this.closeCurrentDialogue);
this.showContent(bs);
}
public void showBalanceSheet() {
BalanceSheetHtmlJPanel bs = new BalanceSheetHtmlJPanel();
bs.setup(this.modelRoot, vl, this.closeCurrentDialogue);
this.showContent(bs);
}
public void showReportBug(){
CopyableTextJPanel ct = new CopyableTextJPanel();
ct.setText(ReportBugTextGenerator.genText());
showContent(ct);
}
public void showBrokerScreen() {
// this is Creating a BrokerScreen Internal Frame in the Main Frame
BrokerScreenHtmlJFrame brokerScreenHtmlJFrame = new BrokerScreenHtmlJFrame();
brokerScreenHtmlJFrame.setup(this.modelRoot, vl,
this.closeCurrentDialogue);
brokerScreenHtmlJFrame.setFrameIcon(null);
showContent(brokerScreenHtmlJFrame);
}
// Shows the Exit Dialog -- @author SonnyZ
public void showExitDialog() {
ConfirmExitJPanel bs = new ConfirmExitJPanel();
bs.setup(this.modelRoot, vl, this.closeCurrentDialogue);
this.showContent(bs);
}
public void showAbout() {
showContent(this.about);
}
public void showHow2Play() {
showContent(this.how2play);
}
public void showJavaProperties() {
showContent(javaProperties);
}
public void showSelectWagons() {
selectWagons.resetSelectedWagons();
selectWagons.setEngineType(selectEngine.getEngineType());
showContent(selectWagons);
}
public void showTerrainInfo(int terrainType) {
this.terrainInfo.setTerrainType(terrainType);
showContent(terrainInfo);
}
public void showTerrainInfo(int x, int y) {
FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
int terrainType = tile.getTerrainTypeID();
showTerrainInfo(terrainType);
}
public void showStationInfo(int stationNumber) {
try {
stationInfo.setStation(stationNumber);
showContent(stationInfo);
} catch (NoSuchElementException e) {
logger.warning("Station " + stationNumber + " does not exist!");
}
}
public void showTrainOrders(int trainId) {
closeContent();
if (trainId != -1) {
trainDialogueJPanel.display(trainId);
showContent(trainDialogueJPanel);
}
}
public void showTrainList() {
if (world.size(modelRoot.getPrincipal(), KEY.TRAINS) > 0) {
final TrainListJPanel trainList = new TrainListJPanel();
trainList.setup(modelRoot, vl, closeCurrentDialogue);
trainList.setShowTrainDetailsActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int id = trainList.getSelectedTrainID();
showTrainOrders(id);
}
});
showContent(trainList);
} else {
modelRoot.setProperty(Property.QUICK_MESSAGE, "There are"
+ " no trains to display!");
}
}
public void showNetworthGraph() {
final NetWorthGraphJPanel worthGraph = new NetWorthGraphJPanel();
worthGraph.setup(modelRoot, vl, closeCurrentDialogue);
showContent(worthGraph);
}
public void showLeaderBoard() {
LeaderBoardJPanel leaderBoardJPanel = new LeaderBoardJPanel();
leaderBoardJPanel.setup(modelRoot, vl, closeCurrentDialogue);
showContent(leaderBoardJPanel);
}
public void showContent(JComponent component) {
closeContent();
JComponent contentPanel;
if (component instanceof JInternalFrame) {
dialogueJInternalFrame = (JInternalFrame) component;
} else {
if (!(component instanceof View)) {
contentPanel = new javax.swing.JPanel();
contentPanel.setLayout(new java.awt.GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.insets = new Insets(7, 7, 7, 7);
contentPanel.add(component, constraints);
constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 1;
constraints.insets = new Insets(7, 7, 7, 7);
contentPanel.add(closeButton, constraints);
} else {
contentPanel = component;
}
dialogueJInternalFrame = new JInternalFrame();
dialogueJInternalFrame.setFrameIcon(null);
dialogueJInternalFrame.getContentPane().add(contentPanel);
dialogueJInternalFrame.pack();
}
/*
* Make sure the size of the dialogue does not exceed the size of the
* frames content pane.
*/
int parentWidth = frame.getContentPane().getWidth();
int parentHeight = frame.getContentPane().getHeight();
Dimension size = dialogueJInternalFrame.getSize();
if (size.width > parentWidth) {
size.width = parentWidth;
}
if (size.height > parentHeight) {
size.height = parentHeight;
}
dialogueJInternalFrame.setSize(size);
dialogueJInternalFrame.setLocation(
(frame.getWidth() - dialogueJInternalFrame.getWidth()) / 2,
(frame.getHeight() - dialogueJInternalFrame.getHeight()) / 2);
frame.getLayeredPane().add(dialogueJInternalFrame,
JLayeredPane.MODAL_LAYER);
dialogueJInternalFrame.setVisible(true);
}
public void closeContent() {
if (null != dialogueJInternalFrame) {
dialogueJInternalFrame.setVisible(false);
frame.getLayeredPane().remove(dialogueJInternalFrame);
dialogueJInternalFrame.dispose();
}
if (null != defaultFocusOwner) {
defaultFocusOwner.requestFocus();
}
}
public void setDefaultFocusOwner(Component defaultFocusOwner) {
this.defaultFocusOwner = defaultFocusOwner;
}
public void showStationOrTerrainInfo(int x, int y) {
FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
TrackRule trackRule = tile.getTrackPiece().getTrackRule();
FreerailsPrincipal principal = modelRoot.getPrincipal();
if (trackRule.isStation()
&& tile.getTrackPiece().getOwnerID() == world.getID(principal)) {
for (int i = 0; i < world.size(principal, KEY.STATIONS); i++) {
StationModel station = (StationModel) world.get(principal,
KEY.STATIONS, i);
if (null != station && station.x == x && station.y == y) {
this.showStationInfo(i);
return;
}
}
throw new IllegalStateException("Couldn't find station at " + x
+ ", " + y);
}
this.showTerrainInfo(x, y);
}
public void listUpdated(KEY key, int index, FreerailsPrincipal principal) {
// do nothing
}
public void itemAdded(KEY key, int index, FreerailsPrincipal principal) {
/*
* Fix for: 910138 After building a train display train orders 910143
* After building station show supply and demand
*/
boolean rightPrincipal = principal
.equals(this.modelRoot.getPrincipal());
if (KEY.TRAINS == key && rightPrincipal) {
this.showTrainOrders(index);
} else if (KEY.STATIONS == key && rightPrincipal) {
this.showStationInfo(index);
}
}
public void itemRemoved(KEY key, int index, FreerailsPrincipal principal) {
// do nothing
}
}

ActiveView

Full name: jfreerails.client.view.ActiveView

Documentation

/**
* Defines a standard method to initiate GUI components that need access to the
* ModelRoot <b> and </b> the ActionRoot.
*
* @author Luke
*
*/

Source Code

/**
* Defines a standard method to initiate GUI components that need access to the
* ModelRoot <b> and </b> the ActionRoot.
*
* @author Luke
*
*/
public interface ActiveView {
void setup(ModelRoot modelRoot, ActionRoot ar, RenderersRoot vl,
ActionListener submitButtonCallBack);
}

Methods

OverviewMapJComponent

Full name: jfreerails.client.view.OverviewMapJComponent

Documentation

/**
* JPanel that displays the overview map and a rectangle showing the region of
* the map currently displayed on the main view.
*
* @author Luke
*/

Source Code

/**
* JPanel that displays the overview map and a rectangle showing the region of
* the map currently displayed on the main view.
*
* @author Luke
*/
public class OverviewMapJComponent extends JPanel {
private static final long serialVersionUID = 3258697585148376888L;
private MapRenderer mapView = new BlankMapRenderer(0.4F);
private final Rectangle mainMapVisRect;
public OverviewMapJComponent(Rectangle r) {
this.setPreferredSize(mapView.getMapSizeInPixels());
mainMapVisRect = r;
}
public void setup(MapRenderer mv) {
mapView = mv;
this.setPreferredSize(mapView.getMapSizeInPixels());
this.setMinimumSize(this.getPreferredSize());
this.setSize(this.getPreferredSize());
if (null != this.getParent()) {
this.getParent().validate();
}
}
@Override
protected void paintComponent(java.awt.Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
java.awt.Rectangle r = this.getVisibleRect();
mapView.paintRect(g2, r);
g2.setColor(Color.WHITE);
g2.drawRect(mainMapVisRect.x, mainMapVisRect.y, mainMapVisRect.width,
mainMapVisRect.height);
}
@Override
public Dimension getPreferredSize() {
return mapView.getMapSizeInPixels();
}
}

BrokerScreenGenerator

Full name: jfreerails.client.view.BrokerScreenGenerator

Documentation

/**
*
* @author smackay
* @author Luke
*/

Source Code

/**
*
* @author smackay
* @author Luke
*/
public class BrokerScreenGenerator {
private static final DecimalFormat DC = new DecimalFormat("#,###");
private FinancialDataGatherer dataGatherer;
private GameCalendar cal;
public String playername;
public String year;
public Money cash;
public Money loansTotal;
public Money netWorth;
public Money pricePerShare;
public String publicShares;
public String treasuryStock;
public String othersRRsStockRows;
/** Creates a new instance of BrokerScreenGenerator */
public BrokerScreenGenerator(ReadOnlyWorld w, FreerailsPrincipal principal) {
dataGatherer = new FinancialDataGatherer(w, principal);
int playerId = w.getID(principal);
this.playername = w.getPlayer(playerId).getName();
this.cal = (GameCalendar) w.get(ITEM.CALENDAR);
GameTime time = w.currentTime();
final int startyear = cal.getYear(time.getTicks());
this.year = String.valueOf(startyear);
this.cash = w.getCurrentBalance(principal);
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
w, principal);
aggregator.setCategory(BOND);
this.loansTotal = aggregator.calculateValue();
this.publicShares = DC.format(dataGatherer.sharesHeldByPublic());
this.netWorth = dataGatherer.netWorth();
StockPrice[] stockPrices = (new StockPriceCalculator(w)).calculate();
this.pricePerShare = stockPrices[playerId].currentPrice;
this.treasuryStock = DC.format(dataGatherer.treasuryStock());
StringBuffer otherRRsStakes = new StringBuffer();
int[] stockInThisRRs = dataGatherer.getStockInThisRRs();
for (int i = 0; i < stockInThisRRs.length; i++) {
if (i != playerId && stockInThisRRs[i] > 0) {
String otherRRName = w.getPlayer(i).getName();
String otherRRStake = DC.format(stockInThisRRs[i]);
otherRRsStakes.append("<tr> ");
otherRRsStakes.append("<td> </td>");
otherRRsStakes.append("<td> </td>");
otherRRsStakes.append("<td>" + otherRRName + "</td>");
otherRRsStakes.append("<td>" + otherRRStake + "</td>");
otherRRsStakes.append("</tr>");
}
}
othersRRsStockRows = otherRRsStakes.toString();
}
}

NetWorthGraphJPanel

Full name: jfreerails.client.view.NetWorthGraphJPanel

Documentation

/**
* A JPanel that displays a graph of the net worth of each of the players
* against time.
*
* @author Luke
*
*/

Source Code

/**
* A JPanel that displays a graph of the net worth of each of the players
* against time.
*
* @author Luke
*
*/
public class NetWorthGraphJPanel extends JPanel implements View {
private static final long serialVersionUID = 3618703010813980982L;
private static final Logger logger = Logger
.getLogger(NetWorthGraphJPanel.class.getName());
private JLabel title = null;
private JLabel yAxisLabel1 = null;
private JLabel yAxisLabel3 = null;
private JLabel yAxisLabel4 = null;
private JLabel yAxisLabel2 = null;
private JLabel xAxisLabel3 = null;
private JLabel xAxisLabel2 = null;
private JLabel xAxisLabel1 = null;
private final Font FONT;
private ArrayList<CompanyDetails> companies = new ArrayList<CompanyDetails>();
private long scaleMax;
private Rectangle graphRect = new Rectangle(44, 50, 380, 245);
ActionListener submitButtonCallBack = null;
/**
* Stores the company details that are used to draw a line and title on the
* graph.
*
* @author Luke
*
*/
static class CompanyDetails {
/** The company's net worth at the end of each year. */
long[] value = new long[100];
/** The colour for the line on the graph. */
final Color color;
/** The company's name. */
final String name;
CompanyDetails(String n, Color c) {
color = c;
name = n;
for (int i = 0; i < 100; i++) {
value[i] = Integer.MIN_VALUE;
}
}
}
/**
* This method initializes
*
*/
public NetWorthGraphJPanel() {
super();
FONT = new java.awt.Font("Bookman Old Style", java.awt.Font.BOLD, 10);
initialize();
// companies.add(new CompanyDetails("Player 1", Color.BLUE));
// companies.add(new CompanyDetails("Player 2", Color.GREEN));
// companies.add(new CompanyDetails("Player 3", Color.CYAN));
// for(int i = 0; i < companies.size(); i++){
// CompanyDetails cd = (CompanyDetails)companies.get(i);
// cd.fillWithRnadomData();
// }
//
// setAppropriateScale();
}
/**
* This method initializes this
*
*/
private void initialize() {
yAxisLabel4 = new JLabel();
yAxisLabel3 = new JLabel();
yAxisLabel2 = new JLabel();
xAxisLabel1 = new JLabel();
xAxisLabel2 = new JLabel();
xAxisLabel3 = new JLabel();
title = new JLabel();
yAxisLabel1 = new JLabel();
this.setLayout(null);
this.setBackground(java.awt.Color.white);
this.setSize(444, 315);
title.setText("Net Worth");
title.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.PLAIN, 24));
title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
title.setLocation(0, 0);
title.setSize(444, 43);
yAxisLabel1.setText("$25");
yAxisLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
yAxisLabel3.setText("$999m");
yAxisLabel4.setText("$999M");
yAxisLabel4.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
yAxisLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
yAxisLabel3.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
yAxisLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
yAxisLabel2.setText("$50");
yAxisLabel2.setLocation(0, 167);
yAxisLabel2.setSize(40, 16);
yAxisLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
yAxisLabel2.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
yAxisLabel1.setLocation(0, 227);
yAxisLabel1.setSize(40, 16);
yAxisLabel3.setLocation(0, 107);
yAxisLabel3.setSize(40, 16);
yAxisLabel4.setLocation(0, 47);
yAxisLabel4.setSize(40, 16);
xAxisLabel3.setText("2000");
xAxisLabel3.setLocation(400, 300);
xAxisLabel3.setSize(40, 17);
xAxisLabel3.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
xAxisLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
xAxisLabel2.setText("1950");
xAxisLabel2.setLocation(210, 300);
xAxisLabel2.setSize(40, 17);
xAxisLabel2.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
xAxisLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
xAxisLabel1.setText("1900");
xAxisLabel1.setLocation(20, 300);
xAxisLabel1.setSize(40, 17);
xAxisLabel1.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
xAxisLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
this.add(xAxisLabel3, null);
this.add(xAxisLabel2, null);
this.add(xAxisLabel1, null);
yAxisLabel1.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
this.add(title, null);
this.add(yAxisLabel1, null);
this.add(yAxisLabel3, null);
this.add(yAxisLabel2, null);
this.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
if (null == submitButtonCallBack) {
System.err.println("mouseClicked");
} else {
submitButtonCallBack.actionPerformed(new ActionEvent(this,
0, null));
}
}
});
this.add(yAxisLabel4, null);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(2f, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_BEVEL));
// Draw guide lines.
g2.setStroke(new BasicStroke(1f, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_BEVEL));
g.setColor(Color.GRAY);
for (int y = 295; y > 50; y -= 60) {
g2.drawLine(graphRect.x, y, 420, y);
}
g2.setStroke(new BasicStroke(2f, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_BEVEL));
// Draw key
for (int i = 0; i < companies.size(); i++) {
int yOffset = i * 20;
CompanyDetails company = companies.get(i);
g2.setColor(company.color);
g2.drawLine(50, 70 + yOffset, 60, 70 + yOffset);
g2.setColor(Color.BLACK);
g2.setFont(FONT);
g.drawString(company.name, 65, 72 + yOffset);
}
// Draw graphs lines
for (int i = 0; i < companies.size(); i++) {
CompanyDetails company = companies.get(i);
g2.setColor(company.color);
for (int year = 1; year < 100; year++) {
if (company.value[year] != Integer.MIN_VALUE
&& company.value[year - 1] != Integer.MIN_VALUE) {
long x1 = year * graphRect.width / 100 + graphRect.x;
long y1 = company.value[year] * graphRect.height / scaleMax;
y1 = Math.max(1, y1);
y1 = graphRect.y + graphRect.height - y1;
long x2 = (year - 1) * graphRect.width / 100 + graphRect.x;
long y2 = company.value[year - 1] * graphRect.height
/ scaleMax;
y2 = Math.max(1, y2);
y2 = graphRect.y + graphRect.height - y2;
g2.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
}
}
}
// Draw axis
g2.setColor(Color.BLACK);
g2.drawLine(graphRect.x, graphRect.y, graphRect.x, graphRect.y
+ graphRect.height);
g2.drawLine(graphRect.x, graphRect.y + graphRect.height, graphRect.x
+ graphRect.width, graphRect.y + graphRect.height);
}
/**
* <p>
* Sets the value of scaleMax subject to the following constraints.
* </P>
* <p>
* (1) scaleMax >= max, where max is the max net worth value.
* </p>
* <p>
* (2) (scaleMax % 4) == 0
* </p>
* <p>
* (3) if max >= 1,000, then (scaleMax % 4,000) == 0
* </p>
* <p>
* (4) if max >= 1,000,000, then (scaleMax % 4,000,000) == 0
* </p>
* <p>
* (5) if max >= 1,000,000,000, then (scaleMax % 4,000,000,000) == 0
* </p>
*/
private void setAppropriateScale() {
long max = 0;
for (int i = 0; i < companies.size(); i++) {
CompanyDetails company = companies.get(i);
for (int year = 0; year < 100; year++) {
long value = company.value[year];
if (value > max) {
max = value;
}
}
}
long increment = 1;
while (scaleMax < max) {
scaleMax = increment;
if (scaleMax < max) {
scaleMax += increment;
int loopCount = 0;
while (scaleMax < max && loopCount < 3) {
scaleMax += increment * 2;
loopCount++;
}
}
increment = increment * 10;
}
/*
* Make sure that if the scale is in k/m/b that each of the quarter
* scales will be divisible by k/m/b.
*/
increment = 1;
for (int i = 0; i < 3; i++) {
increment = increment * 1000;
if (scaleMax >= 8 * increment && scaleMax < 12 * increment) {
scaleMax = 12 * increment;
} else if (scaleMax >= 4 * increment && scaleMax < 8 * increment) {
scaleMax = 8 * increment;
} else if (scaleMax >= 1 * increment && scaleMax < 4 * increment) {
scaleMax = 4 * increment;
}
}
if (scaleMax < 100) {
scaleMax = 100;
}
long quarterScale = scaleMax / 4;
yAxisLabel1.setText(getYScaleString(quarterScale));
yAxisLabel2.setText(getYScaleString(quarterScale * 2));
yAxisLabel3.setText(getYScaleString(quarterScale * 3));
yAxisLabel4.setText(getYScaleString(quarterScale * 4));
}
private String getYScaleString(long value) {
String abv;
if (value >= 1000000000) {
value = value / 1000000000;
abv = "b";
} else if (value >= 1000000) {
value = value / 1000000;
abv = "m";
} else if (value >= 1000) {
value = value / 1000;
abv = "k";
} else {
abv = "";
}
return "$" + String.valueOf(value) + abv;
}
public void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
this.submitButtonCallBack = closeAction;
ReadOnlyWorld world = modelRoot.getWorld();
companies = new ArrayList<CompanyDetails>();
GameCalendar calender = (GameCalendar) world.get(ITEM.CALENDAR);
int startYear = calender.getYear(0);
int endYear = startYear + 100;
GameTime currentTime = world.currentTime();
int currentYear = calender.getYear(currentTime.getTicks());
xAxisLabel1.setText(String.valueOf(startYear));
xAxisLabel2.setText(String.valueOf(startYear + 50));
xAxisLabel3.setText(String.valueOf(endYear));
for (int i = 0; i < world.getNumberOfPlayers(); i++) {
Color c = PlayerColors.getColor(i);
Player player = world.getPlayer(i);
String name = player.getName();
logger.fine("Adding player " + name + " to net worth graph.");
CompanyDetails cd = new CompanyDetails(name, c);
GameTime[] times = new GameTime[101];
for (int year = 0; year < 101; year++) {
int ticks = calender.getTicks(startYear + year - 1);
times[year] = new GameTime(ticks);
}
TransactionAggregator aggregator = new NetWorthCalculator(world,
player.getPrincipal());
aggregator.setTimes(times);
Money[] values = aggregator.calculateValues();
int stopYear = currentYear - startYear + 1;
for (int year = 0; year < stopYear; year++) {
cd.value[year] = values[year].getAmount();
}
companies.add(cd);
}
setAppropriateScale();
}
} // @jve:decl-index=0:visual-constraint="10,10"

ShowJavaProperties

Full name: jfreerails.client.view.ShowJavaProperties

Documentation

/**
* This class returns the Java System Properties as an HTML table.
*
* @author Luke
*
*/

Source Code

/**
* This class returns the Java System Properties as an HTML table.
*
* @author Luke
*
*/
public class ShowJavaProperties {
public static final int TABLE_WIDTH = 500;
private static final Logger logger = Logger
.getLogger(ShowJavaProperties.class.getName());
public static void main(String[] args) {
logger.info(getPropertiesHtmlString());
}
public static String getPropertiesHtmlString() {
Properties p = System.getProperties();
StringBuffer sb = new StringBuffer();
/* We set the width of the table so that its text word-wraps. */
sb.append("<html><h3>Java System Properties</h3><table width =\""
+ TABLE_WIDTH + "\" align = \"left\" valign = \"top\">\n");
Enumeration keys = p.keys();
//We use an ArrayList so that the keys can be sorted into alphabetical order
ArrayList<String> list = new ArrayList<String>();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
list.add(key);
}
Collections.sort(list);
for(String key : list){
String value = p.getProperty(key);
/*
* Insert a line break after each ";". This makes reading classpath
* elements easier.
*/
value = value.replaceAll(";", ";<br>");
sb
.append("<tr><td>" + key + " </td><td> " + value
+ "</td></tr>\n");
}
sb.append("</table></html>\n");
return sb.toString();
}
}

SelectWagonsJPanel

Full name: jfreerails.client.view.SelectWagonsJPanel

Documentation

/**
* This JPanel lets the user add wagons to a train.
*
* @author lindsal8
*
*/

Source Code

/**
* This JPanel lets the user add wagons to a train.
*
* @author lindsal8
*
*/
public class SelectWagonsJPanel extends javax.swing.JPanel implements View {
private static final long serialVersionUID = 3905239009449095220L;
private final GraphicsConfiguration defaultConfiguration = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
private final Image stationView;
private final ArrayList<Integer> wagons = new ArrayList<Integer>();
private int engineType = 0;
private RenderersRoot rr;
public SelectWagonsJPanel() {
initComponents();
updateMaxWagonsText();
URL url = SelectWagonsJPanel.class
.getResource("/jfreerails/data/station.gif");
Image tempImage = (new javax.swing.ImageIcon(url)).getImage();
stationView = defaultConfiguration.createCompatibleImage(tempImage
.getWidth(null), tempImage.getHeight(null),
Transparency.BITMASK);
Graphics g = stationView.getGraphics();
g.drawImage(tempImage, 0, 0, null);
}
public void resetSelectedWagons() {
this.wagons.clear();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
wagonTypesJList = new javax.swing.JList();
okjButton = new javax.swing.JButton();
clearjButton = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
setBackground(new java.awt.Color(0, 255, 51));
setMinimumSize(new java.awt.Dimension(640, 400));
setPreferredSize(new java.awt.Dimension(620, 380));
jPanel1.setLayout(new java.awt.GridBagLayout());
jPanel1.setMinimumSize(new java.awt.Dimension(170, 300));
jPanel1.setPreferredSize(new java.awt.Dimension(170, 300));
wagonTypesJList.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyTyped(java.awt.event.KeyEvent evt) {
wagonTypesJListKeyTyped(evt);
}
});
wagonTypesJList.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
wagonTypesJListMouseClicked(evt);
}
});
jScrollPane1.setViewportView(wagonTypesJList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel1.add(jScrollPane1, gridBagConstraints);
okjButton.setText("OK");
okjButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonAction(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
jPanel1.add(okjButton, gridBagConstraints);
clearjButton.setText("Clear");
clearjButton.setActionCommand("clear");
clearjButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel1.add(clearjButton, gridBagConstraints);
jLabel1.setFont(new java.awt.Font("Dialog", 0, 10));
jLabel1.setText("The maximum train length is 6 wagons");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 8);
jPanel1.add(jLabel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(20, 400, 70, 10);
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
add(jPanel1, gridBagConstraints);
}// GEN-END:initComponents
private void okButtonAction(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_okButtonAction
// Add your handling code here:
} // GEN-LAST:event_okButtonAction
private void wagonTypesJListMouseClicked(java.awt.event.MouseEvent evt) { // GEN-FIRST:event_wagonTypesJListMouseClicked
// Add your handling code here:
addwagon();
} // GEN-LAST:event_wagonTypesJListMouseClicked
private void wagonTypesJListKeyTyped(java.awt.event.KeyEvent evt) { // GEN-FIRST:event_wagonTypesJListKeyTyped
// Add your handling code here:
if (KeyEvent.VK_ENTER == evt.getKeyCode()) {
addwagon();
} else {
}
} // GEN-LAST:event_wagonTypesJListKeyTyped
// Adds the wagon selected in the list to the train consist.
private void addwagon() {
if (wagons.size() < TrainModel.MAX_NUMBER_OF_WAGONS) {
int type = wagonTypesJList.getSelectedIndex();
wagons.add(new Integer(type));
updateMaxWagonsText();
this.repaint();
}
}
private void updateMaxWagonsText() {
if (wagons.size() >= TrainModel.MAX_NUMBER_OF_WAGONS) {
jLabel1.setText("Max train length is "
+ TrainModel.MAX_NUMBER_OF_WAGONS + " wagons");
} else {
jLabel1.setText("");
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton1ActionPerformed
// Add your handling code here:
wagons.clear();
jLabel1.setText("");
this.repaint();
} // GEN-LAST:event_jButton1ActionPerformed
@Override
public void paint(Graphics g) {
// paint the background
g.drawImage(this.stationView, 0, 0, null);
int x = this.getWidth();
int y = 330;
final int SCALED_IMAGE_HEIGHT = 50;
// paint the wagons
for (int i = this.wagons.size() - 1; i >= 0; i--) { // Count down so we
// paint the wagon
// at the end of the
// train first.
Integer type = wagons.get(i);
Image image = rr.getWagonImages(type.intValue()).getSideOnImage();
int scaledWidth = image.getWidth(null) * SCALED_IMAGE_HEIGHT
/ image.getHeight(null);
x -= scaledWidth;
g.drawImage(image, x, y, scaledWidth, SCALED_IMAGE_HEIGHT, null);
}
// paint the engine
if (-1 != this.engineType) { // If an engine is selected.
Image image = rr.getEngineImages(engineType).getSideOnImage();
int scaledWidth = (image.getWidth(null) * SCALED_IMAGE_HEIGHT)
/ image.getHeight(null);
x -= scaledWidth;
g.drawImage(image, x, y, scaledWidth, SCALED_IMAGE_HEIGHT, null);
}
this.paintChildren(g);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton clearjButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton okjButton;
private javax.swing.JList wagonTypesJList;
// End of variables declaration//GEN-END:variables
final private class WagonCellRenderer implements ListCellRenderer {
private final Component[] labels;
final RenderersRoot rr;
public WagonCellRenderer(World2ListModelAdapter w2lma, RenderersRoot s) {
rr = s;
labels = new Component[w2lma.getSize()];
for (int i = 0; i < w2lma.getSize(); i++) {
JLabel label = new JLabel();
label.setFont(new java.awt.Font("Dialog", 0, 12));
Image image = rr.getWagonImages(i).getSideOnImage();
int height = image.getHeight(null);
int width = image.getWidth(null);
int scale = height / 10;
ImageIcon icon = new ImageIcon(image.getScaledInstance(width
/ scale, height / scale, Image.SCALE_FAST));
label.setIcon(icon);
labels[i] = label;
}
}
public Component getListCellRendererComponent(JList list, Object value, /*
* value
* to
* display
*/
int index, /* cell index */
boolean isSelected, /* is the cell selected */
boolean cellHasFocus) /* the list and the cell have the focus */{
if (index >= 0 && index < labels.length) {
CargoType cargoType = (CargoType) value;
String text = "<html><body>"
+ (isSelected ? "<strong>" : "")
+ cargoType.getDisplayName()
+ (isSelected ? "</strong>"
: "&nbsp;&nbsp;&nbsp;&nbsp;"/*
* padding to stop
* word wrap due to
* greater width of
* strong font
*/) + "</body></html>";
((JLabel) labels[index]).setText(text);
return labels[index];
}
return null;
}
}
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
World2ListModelAdapter w2lma = new World2ListModelAdapter(
mr.getWorld(), SKEY.CARGO_TYPES);
this.wagonTypesJList.setModel(w2lma);
this.rr = vl;
WagonCellRenderer wagonCellRenderer = new WagonCellRenderer(w2lma,
rr);
this.wagonTypesJList.setCellRenderer(wagonCellRenderer);
this.okjButton.addActionListener(closeAction);
}
public int[] getWagons() {
int[] wagonsArray = new int[wagons.size()];
for (int i = 0; i < wagons.size(); i++) {
Integer type = wagons.get(i);
wagonsArray[i] = type.intValue();
}
return wagonsArray;
}
public void setEngineType(int engineType) {
this.engineType = engineType;
}
}

HtmlJPanel

Full name: jfreerails.client.view.HtmlJPanel

Documentation

/**
* This JPanel displays a HTML document read from a URL.
*
* @author Luke
*/

Source Code

/**
* This JPanel displays a HTML document read from a URL.
*
* @author Luke
*/
public class HtmlJPanel extends javax.swing.JPanel implements View {
private static final long serialVersionUID = 4120848850266371126L;
private static final Logger logger = Logger.getLogger(HtmlJPanel.class
.getName());
HtmlJPanel() {
initComponents();
}
public HtmlJPanel(URL url) {
initComponents();
setHtml(loadText(url));
}
public HtmlJPanel(URL url, HashMap context) {
initComponents();
String template = loadText(url);
String populatedTemplate = populateTokens(template, context);
setHtml(populatedTemplate);
}
public HtmlJPanel(String html) {
initComponents();
setHtml(html);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jScrollPane1 = new javax.swing.JScrollPane();
htmlJLabel = new javax.swing.JLabel();
done = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
setMinimumSize(new java.awt.Dimension(400, 300));
jScrollPane1
.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
htmlJLabel.setFont(new java.awt.Font("Dialog", 0, 12));
htmlJLabel.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
jScrollPane1.setViewportView(htmlJLabel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(jScrollPane1, gridBagConstraints);
done.setText("Close");
done.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
doneActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(done, gridBagConstraints);
}// GEN-END:initComponents
private void doneActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_doneActionPerformed
// TODO add your handling code here:
}// GEN-LAST:event_doneActionPerformed
public void setup(ModelRoot m, RenderersRoot vl,
Action closeAction) {
this.done.setAction(closeAction);
}
/** Load the help text from file. */
String loadText(final URL htmlUrl) {
try {
InputStream in = htmlUrl.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
new DataInputStream(in)));
String line;
String text = "";
while ((line = br.readLine()) != null) {
text = text + line;
}
return text;
} catch (Exception e) {
e.printStackTrace();
logger.warning(htmlUrl.toString());
return "Couldn't read: " + htmlUrl;
}
}
void setHtml(String s) {
htmlJLabel.setText(s);
}
static String populateTokens(String template, Object context) {
StringTokenizer tokenizer = new StringTokenizer(template, "$");
String output = "";
while (tokenizer.hasMoreTokens()) {
output += tokenizer.nextToken();
if (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
String value;
if (context instanceof HashMap) {
value = (String) ((HashMap) context).get(token);
} else {
try {
StringTokenizer t2 = new StringTokenizer(token, ".");
value = null;
Object o = context;
while (t2.hasMoreTokens()) {
String subToken = t2.nextToken();
Field field = o.getClass().getField(subToken);
o = field.get(o);
}
value = o.toString();
} catch (Exception e) {
e.printStackTrace();
throw new NoSuchElementException(token);
}
}
output += value;
}
}
return output;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton done;
private javax.swing.JLabel htmlJLabel;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
}

StationBuildModel

Full name: jfreerails.client.view.StationBuildModel

Documentation

/**
* This class provides the UI model for building a station. The mode of
* operation is as follows:
* <ol>
* <li>Select a station to build by calling ActionPerformed() on the choose
* Action.
* <li>Set the position to build.
* <li>call actionPerformed on the build Action
* <li> alternatively, call actionPerformed on the cancel Action
* </ol>
*
* @author rob
*/

Source Code

/**
* This class provides the UI model for building a station. The mode of
* operation is as follows:
* <ol>
* <li>Select a station to build by calling ActionPerformed() on the choose
* Action.
* <li>Set the position to build.
* <li>call actionPerformed on the build Action
* <li> alternatively, call actionPerformed on the cancel Action
* </ol>
*
* @author rob
*/
public class StationBuildModel {
/*
* 100 010 001 = 0x111
*/
private static final int trackTemplate = TrackConfiguration
.from9bitTemplate(0x111).get9bitTemplate();
/**
* Vector of StationBuildAction. Actions which represent stations which can
* be built
*/
private final Vector<Action> stationChooseActions = new Vector<Action>();
/**
* Whether the station's position can should change when the mouse moves.
*/
private boolean positionFollowsMouse = true;
private final StationBuildAction stationBuildAction = new StationBuildAction();
private final StationCancelAction stationCancelAction = new StationCancelAction();
private final StationBuilder stationBuilder;
private final ModelRoot modelRoot;
private final HashMap<Integer, Action> id2Action = new HashMap<Integer, Action>();
public StationBuildModel(StationBuilder sb, RenderersRoot rr, ModelRoot mr) {
stationBuilder = sb;
modelRoot = mr;
ReadOnlyWorld world = modelRoot.getWorld();
for (int i = 0; i < world.size(SKEY.TRACK_RULES); i++) {
final TrackRule trackRule = (TrackRule) world.get(
SKEY.TRACK_RULES, i);
if (trackRule.isStation()) {
TrackPieceRenderer renderer = rr.getTrackPieceView(i);
StationChooseAction action = new StationChooseAction(i);
String trackType = trackRule.getTypeName();
Money price = trackRule.getFixedCost();
String shortDescrpt = Utils.capitalizeEveryWord(trackType)
+ " $" + price.toString();
action.putValue(Action.SHORT_DESCRIPTION, shortDescrpt);
action.putValue(Action.NAME, "Build " + trackType);
action.putValue(Action.SMALL_ICON, new ImageIcon(renderer
.getTrackPieceIcon(trackTemplate)));
stationChooseActions.add(action);
id2Action.put(new Integer(i), action);
}
}
}
public Action getStationChooseAction(Integer ruleID) {
return id2Action.get(ruleID);
}
public Action[] getStationChooseActions() {
return stationChooseActions.toArray(new Action[stationChooseActions.size()]);
}
private class StationChooseAction extends AbstractAction {
private static final long serialVersionUID = 3257290240279458098L;
private final int actionId;
public StationChooseAction(int actionId) {
this.actionId = actionId;
}
public void actionPerformed(ActionEvent e) {
stationBuilder.setStationType(actionId);
TrackRule trackRule = (TrackRule) modelRoot.getWorld().get(
SKEY.TRACK_RULES, actionId);
// Show the relevant station radius when the station type's menu
// item
// gets focus.
stationBuildAction.putValue(StationBuildAction.STATION_RADIUS_KEY,
new Integer(trackRule.getStationRadius()));
stationBuildAction.setEnabled(true);
}
}
private class StationCancelAction extends AbstractAction {
private static final long serialVersionUID = 3256441421581203252L;
public void actionPerformed(ActionEvent e) {
stationBuildAction.setEnabled(false);
}
}
/**
* This action builds the station.
*/
public class StationBuildAction extends AbstractAction {
private static final long serialVersionUID = 3905236827739926833L;
/**
* This key can be used to set the position where the station is to be
* built as a Point object.
*/
public final static String STATION_POSITION_KEY = "STATION_POSITION_KEY";
/**
* This key can be used to retrieve the radius of the currently selected
* station as an Integer value. Don't bother writing to it!
*/
public final static String STATION_RADIUS_KEY = "STATION_RADIUS_KEY";
StationBuildAction() {
setEnabled(false);
}
public void actionPerformed(ActionEvent e) {
Point value = (Point) stationBuildAction
.getValue(StationBuildAction.STATION_POSITION_KEY);
MoveStatus ms = stationBuilder.buildStation(new ImPoint(value.x,
value.y));
String message = null;
if (ms.isOk()) {
stationBuildAction.setEnabled(false);
} else {
message = ms.message;
}
modelRoot.setProperty(ModelRoot.Property.CURSOR_MESSAGE, message);
}
}
public boolean canBuildStationHere() {
Point p = (Point) stationBuildAction
.getValue(StationBuildAction.STATION_POSITION_KEY);
return stationBuilder.tryBuildingStation(new ImPoint(p.x, p.y)).ok;
}
public Action getStationCancelAction() {
return stationCancelAction;
}
public StationBuildAction getStationBuildAction() {
return stationBuildAction;
}
public boolean isPositionFollowsMouse() {
return positionFollowsMouse;
}
public void setPositionFollowsMouse(boolean positionFollowsMouse) {
this.positionFollowsMouse = positionFollowsMouse;
}
}

World2ListModelAdapter

Full name: jfreerails.client.view.World2ListModelAdapter

Documentation

/**
* Converts the interface of a list on the world object to a ListModel interface
* that can be used by JLists. Currently, change notification is <b>not</b>
* implemented (null elements are skipped).
*
* @author Luke
*
*/

Source Code

/**
* Converts the interface of a list on the world object to a ListModel interface
* that can be used by JLists. Currently, change notification is <b>not</b>
* implemented (null elements are skipped).
*
* @author Luke
*
*/
public class World2ListModelAdapter implements ListModel {
private final ReadOnlyWorld w;
private final NonNullElements elements;
public World2ListModelAdapter(ReadOnlyWorld world, SKEY key) {
this.w = world;
if (null == key)
throw new NullPointerException();
if (null == w)
throw new NullPointerException();
elements = new NonNullElements(key, world);
}
public World2ListModelAdapter(ReadOnlyWorld world, KEY key,
FreerailsPrincipal p) {
this.w = world;
if (null == key)
throw new NullPointerException();
if (null == p)
throw new NullPointerException();
if (null == w)
throw new NullPointerException();
// Check that the principal exists.
if (!world.isPlayer(p))
throw new IllegalArgumentException(p.getName());
elements = new NonNullElements(key, world, p);
}
public int getSize() {
return elements.size();
}
public Object getElementAt(int i) {
elements.gotoRow(i);
return elements.getElement();
}
public void addListDataListener(ListDataListener arg0) {
// TODO Auto-generated method stub
}
public void removeListDataListener(ListDataListener arg0) {
// TODO Auto-generated method stub
}
}

DateJLabel

Full name: jfreerails.client.view.DateJLabel

Documentation

/**
* This JLabel shows the current date.
*
* @author Luke
*
*/

Source Code

/**
* This JLabel shows the current date.
*
* @author Luke
*
*/
public class DateJLabel extends JLabel implements View {
private static final long serialVersionUID = 3689348840578757942L;
private ReadOnlyWorld w;
public DateJLabel() {
this.setText(" ");
}
@Override
protected void paintComponent(Graphics g) {
if (null != w) {
GameTime time = w.currentTime();
GameCalendar gameCalendar = (GameCalendar) w.get(ITEM.CALENDAR);
String s = gameCalendar.getYearAndMonth(time.getTicks());
super.setText(s);
}
super.paintComponent(g);
}
public void setup(ModelRoot model, RenderersRoot vl,
Action closeAction) {
this.w = model.getWorld();
}
}

TrainOrdersListModel

Full name: jfreerails.client.view.TrainOrdersListModel

Documentation

/**
* AbstractListModel used by {@link TrainScheduleJPanel} to display the orders
* making up a train schedule.
*
* @author Luke Lindsay
*/

Source Code

/**
* AbstractListModel used by {@link TrainScheduleJPanel} to display the orders
* making up a train schedule.
*
* @author Luke Lindsay
*/
public class TrainOrdersListModel extends AbstractListModel {
private static final long serialVersionUID = 3762537827703009847L;
private final int trainNumber;
private final ReadOnlyWorld w;
private final FreerailsPrincipal principal;
public static final int DONT_GOTO = 0;
public static final int GOTO_NOW = 1;
public static final int GOTO_AFTER_PRIORITY_ORDERS = 2;
/**
* This class holds the values that are needed by the ListCellRender.
* TrainOrdersListModel.getElementAt(int index) returns an instance of this
* class.
*/
public static class TrainOrdersListElement {
public final boolean isPriorityOrder;
public final int gotoStatus;
public final TrainOrdersModel order;
public final int trainNumber;
public TrainOrdersListElement(boolean isPriorityOrder, int gotoStatus,
TrainOrdersModel order, int trainNumber) {
this.isPriorityOrder = isPriorityOrder;
this.gotoStatus = gotoStatus;
this.order = order;
this.trainNumber = trainNumber;
}
}
public TrainOrdersListModel(ReadOnlyWorld w, int trainNumber,
FreerailsPrincipal p) {
this.trainNumber = trainNumber;
this.w = w;
this.principal = p;
assert (null != getSchedule());
}
public Object getElementAt(int index) {
Schedule s = getSchedule();
int gotoStatus;
if (s.getNextScheduledOrder() == index) {
if (s.hasPriorityOrders()) {
gotoStatus = GOTO_AFTER_PRIORITY_ORDERS;
} else {
gotoStatus = GOTO_NOW;
}
} else {
if (s.hasPriorityOrders() && 0 == index) {
// These orders are the priority orders.
gotoStatus = GOTO_NOW;
} else {
gotoStatus = DONT_GOTO;
}
}
boolean isPriorityOrders = 0 == index && s.hasPriorityOrders();
TrainOrdersModel order = getSchedule().getOrder(index);
return new TrainOrdersListElement(isPriorityOrders, gotoStatus, order,
trainNumber);
}
public int getSize() {
Schedule s = getSchedule();
int size = 0;
if (s != null) {
size = s.getNumOrders();
}
return size;
}
public void fireRefresh() {
super.fireContentsChanged(this, 0, getSize());
}
private Schedule getSchedule() {
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
trainNumber);
ImmutableSchedule sched = null;
if (train != null) {
sched = (ImmutableSchedule) w.get(principal, KEY.TRAIN_SCHEDULES, train
.getScheduleID());
}
return sched;
}
}

BrokerJFrame

Full name: jfreerails.client.view.BrokerJFrame

Documentation

/**
* @author smackay
* @author Luke
*/

Source Code

/**
* @author smackay
* @author Luke
*/
public class BrokerJFrame extends javax.swing.JInternalFrame {
private static final long serialVersionUID = 4121409622587815475L;
private static final Logger logger = Logger.getLogger(BrokerJFrame.class
.getName());
/** Creates new form BrokerJFrame */
BrokerJFrame() {
initComponents();
}
public BrokerJFrame(URL url) {
initComponents();
setHtml(loadText(url));
}
public BrokerJFrame(URL url, HashMap context) {
initComponents();
String template = loadText(url);
String populatedTemplate = populateTokens(template, context);
setHtml(populatedTemplate);
}
public BrokerJFrame(String html) {
initComponents();
setHtml(html);
}
public void setup(ModelRoot m, RenderersRoot vl,
Action closeAction) {
this.done.setAction(closeAction);
}
/** Load the help text from file. */
String loadText(final URL htmlUrl) {
try {
InputStream in = htmlUrl.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
new DataInputStream(in)));
String line;
String text = "";
while ((line = br.readLine()) != null) {
text = text + line;
}
return text;
} catch (Exception e) {
e.printStackTrace();
logger.warning(htmlUrl.toString());
return "Couldn't read: " + htmlUrl;
}
}
void setHtml(String s) {
htmlJLabel.setText(s);
}
public String populateTokens(String template, Object context) {
StringTokenizer tokenizer = new StringTokenizer(template, "$");
String output = "";
while (tokenizer.hasMoreTokens()) {
output += tokenizer.nextToken();
if (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
String value;
if (context instanceof HashMap) {
value = (String) ((HashMap) context).get(token);
} else {
try {
Field field = context.getClass().getField(token);
value = field.get(context).toString();
} catch (Exception e) {
e.printStackTrace();
throw new NoSuchElementException(token);
}
}
output += value;
}
}
return output;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
htmlJLabel = new javax.swing.JLabel();
done = new javax.swing.JButton();
brokerMenu = new javax.swing.JMenuBar();
bonds = new javax.swing.JMenu();
issueBond = new javax.swing.JMenuItem();
repayBond = new javax.swing.JMenuItem();
stocks = new javax.swing.JMenu();
getContentPane().setLayout(new java.awt.GridBagLayout());
jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jPanel1.setLayout(new java.awt.BorderLayout());
htmlJLabel.setFont(new java.awt.Font("Dialog", 0, 12));
htmlJLabel.setText("sdfa");
htmlJLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
htmlJLabel.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
jPanel1.add(htmlJLabel, java.awt.BorderLayout.CENTER);
jScrollPane1.setViewportView(jPanel1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(jScrollPane1, gridBagConstraints);
done.setText("Close");
done.setVerifyInputWhenFocusTarget(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
getContentPane().add(done, gridBagConstraints);
bonds.setText("Bonds");
issueBond.setText("Issue Bond");
bonds.add(issueBond);
repayBond.setText("Repay Bond");
bonds.add(repayBond);
brokerMenu.add(bonds);
stocks.setText("Stocks");
brokerMenu.add(stocks);
setJMenuBar(brokerMenu);
pack();
}
// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JMenu bonds;
javax.swing.JMenuBar brokerMenu;
javax.swing.JButton done;
javax.swing.JLabel htmlJLabel;
javax.swing.JMenuItem issueBond;
javax.swing.JPanel jPanel1;
javax.swing.JScrollPane jScrollPane1;
javax.swing.JMenuItem repayBond;
javax.swing.JMenu stocks;
// End of variables declaration//GEN-END:variables
}

KeyCode2OneTileMoveVector

Full name: jfreerails.client.view.KeyCode2OneTileMoveVector

Documentation

/**
* Maps keys to OneTileMoveVectors.
*
* @author Luke
*
*/

Source Code

/**
* Maps keys to OneTileMoveVectors.
*
* @author Luke
*
*/
public class KeyCode2OneTileMoveVector {
private static final HashMap<Integer, Step> keycode2vector = new HashMap<Integer, Step>();
static {
// Set up key mappings...
// Num pad with num lock on
keycode2vector.put(new Integer(KeyEvent.VK_NUMPAD1), Step.SOUTH_WEST);
keycode2vector.put(new Integer(KeyEvent.VK_NUMPAD2), Step.SOUTH);
keycode2vector.put(new Integer(KeyEvent.VK_NUMPAD3), Step.SOUTH_EAST);
keycode2vector.put(new Integer(KeyEvent.VK_NUMPAD4), Step.WEST);
keycode2vector.put(new Integer(KeyEvent.VK_NUMPAD6), Step.EAST);
keycode2vector.put(new Integer(KeyEvent.VK_NUMPAD7), Step.NORTH_WEST);
keycode2vector.put(new Integer(KeyEvent.VK_NUMPAD8), Step.NORTH);
keycode2vector.put(new Integer(KeyEvent.VK_NUMPAD9), Step.NORTH_EAST);
// Num pad with num lock off
keycode2vector.put(new Integer(KeyEvent.VK_END), Step.SOUTH_WEST);
keycode2vector.put(new Integer(KeyEvent.VK_DOWN), Step.SOUTH);
keycode2vector.put(new Integer(KeyEvent.VK_PAGE_DOWN), Step.SOUTH_EAST);
keycode2vector.put(new Integer(KeyEvent.VK_LEFT), Step.WEST);
keycode2vector.put(new Integer(KeyEvent.VK_RIGHT), Step.EAST);
keycode2vector.put(new Integer(KeyEvent.VK_HOME), Step.NORTH_WEST);
keycode2vector.put(new Integer(KeyEvent.VK_UP), Step.NORTH);
keycode2vector.put(new Integer(KeyEvent.VK_PAGE_UP), Step.NORTH_EAST);
}
/** Returns the OneTileMoveVector that is mapped to the specified keycode. */
public static Step getInstanceMappedToKey(int keycode)
throws NoSuchElementException {
Integer integer = new Integer(keycode);
if (!keycode2vector.containsKey(integer)) {
throw new NoSuchElementException(String.valueOf(keycode));
}
return keycode2vector.get(integer);
}
}

ServerControlModel

Full name: jfreerails.client.view.ServerControlModel

Documentation

/**
* Exposes the ServerControlInterface to client UI implementations.
*
* @author rob
* @author Luke
* @author MystiqueAgent
*/

Source Code

/**
* Exposes the ServerControlInterface to client UI implementations.
*
* @author rob
* @author Luke
* @author MystiqueAgent
*/
public class ServerControlModel implements ModelRootListener{
private class LoadGameAction extends AbstractAction {
private static final long serialVersionUID = 3616451215278682931L;
public LoadGameAction() {
putValue(NAME, "Load Game");
putValue(MNEMONIC_KEY, new Integer(76));
}
public void actionPerformed(ActionEvent e) {
dbc.showSelectSavedGame2Load();
/*
ImStringList files = (ImStringList)modelRoot.getProperty(Property.SAVED_GAMES_LIST);
Object[] saves = new Object[files.size()];
for (int i = 0; i < files.size(); i++) {
saves[i] = files.get(i);
}
// Display a JOptionPane that lists the existing saved games
try {
Object showInputDialog = JOptionPane.showInputDialog(null,
"Saved Games:", "Select game to load",
JOptionPane.INFORMATION_MESSAGE, null, saves, saves[0]);
String filename = showInputDialog.toString();
// Load the game chosen
Message2Server message2 = new LoadGameMessage2Server(1,
filename);
modelRoot.sendCommand(message2);
} catch (Exception exept) {
// <Hack>
// When no saved game is selected, or one that doesnt exist,
// nothing changes
// </.Hack>
}
*/
}
}
private class NewGameAction extends AbstractAction {
private static final long serialVersionUID = 3690758388631745337L;
public NewGameAction(String s) {
if (s == null) {
putValue(NAME, "New Game...");
} else {
putValue(NAME, s);
putValue(ACTION_COMMAND_KEY, s);
}
}
public void actionPerformed(ActionEvent e) {
String mapName = e.getActionCommand();
if (mapName != null) {
Message2Server message2 = new NewGameMessage2Server(1, mapName);
modelRoot.sendCommand(message2);
}
}
}
private class SaveGameAction extends AbstractAction {
private static final long serialVersionUID = 3905808578064562480L;
public SaveGameAction() {
putValue(NAME, "Save Game");
putValue(MNEMONIC_KEY, new Integer(83));
}
public void actionPerformed(ActionEvent e) {
dbc.showSaveGame();
/*
try {
// @SonnyZ
// Show a JOptionPane that takes in a string from a text box
String filename = JOptionPane.showInputDialog(null,
"Saved Game Name:", "Save Game",
JOptionPane.QUESTION_MESSAGE, null, null,
modelRoot.getPrincipal().getName()).toString();
// Save the current game using the string
modelRoot.setProperty(Property.QUICK_MESSAGE, "Saved game "
+ filename);
Message2Server message2 = new SaveGameMessage2Server(1,
filename + ".sav");
modelRoot.sendCommand(message2);
loadGameAction.setEnabled(true);
} catch (Exception except) {
}
*/
}
}
private class SetTargetTicksPerSecondAction extends AbstractAction {
private static final long serialVersionUID = 3256437014978048052L;
final int speed;
/**
* Same as the constructor above but it enables also to associate a
* <code>keyEvent</code> with the action.
*
* @param name
* action name
* @param speed
* speed
* @param keyEvent
* associated key event. Use values from
* <code>KeyEvent</class>.
*
* by MystiqueAgent
*/
public SetTargetTicksPerSecondAction(String name, int speed,
int keyEvent) {
putValue(NAME, name);
this.speed = speed;
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(keyEvent, 0));
}
public void actionPerformed(ActionEvent e) {
int speed2set = speed;
if (speed == 0) { // pausing/unpausing
speed2set = -1 * getTargetTicksPerSecond();
}
modelRoot.doMove(ChangeGameSpeedMove.getMove(modelRoot.getWorld(),
new GameSpeed(speed2set)));
}
}
private final Action loadGameAction = new LoadGameAction();
private ModelRootImpl modelRoot;
private final Action newGameAction = new NewGameAction(null);
private final Action saveGameAction = new SaveGameAction();
private ActionAdapter selectMapActions;
private final SetTargetTicksPerSecondAction[] speedActions = new SetTargetTicksPerSecondAction[] {
new SetTargetTicksPerSecondAction("Pause", 0, KeyEvent.VK_P),
new SetTargetTicksPerSecondAction("Slow", 10, KeyEvent.VK_1),
new SetTargetTicksPerSecondAction("Moderate", 30, KeyEvent.VK_2),
new SetTargetTicksPerSecondAction("Fast", 70, KeyEvent.VK_3),
};
private final ActionAdapter targetTicksPerSecondActions = new ActionAdapter(
speedActions, 0);
private DialogueBoxController dbc;
public ServerControlModel(ModelRootImpl mr) {
this.modelRoot = mr;
mr.addPropertyChangeListener(this);
setServerControlInterface();
}
/**
* Returns human readable string description of <code>tickPerSecond</code>
* number. Looks for <code>tickPerSecond</code> in
* <code>targetTicksPerSecondActions</code>. If appropriate action is not
* found returns first greater value or the greatest value.
*
* @param tickPerSecond
* int
* @return String human readable description
*/
public String getGameSpeedDesc(int tickPerSecond) {
SetTargetTicksPerSecondAction action = null;
for (int i = 0; i < speedActions.length; i++) {
action = speedActions[i];
if (action.speed >= tickPerSecond)
break;
}
return (String) action.getValue(Action.NAME);
}
/**
* @return an action to load a game.
*/
public Action getLoadGameAction() {
return loadGameAction;
}
/**
* @return an ActionAdapter representing a list of actions representing
* valid map names.
*/
public ActionAdapter getMapNames() {
return selectMapActions;
}
/**
* When calling this action, set the action command string to the desired
* map name, or call the appropriate selectMapAction.
*
* @return an action to start a new game
*/
public Action getNewGameAction() {
return newGameAction;
}
/**
* @return an action to save a game TODO The action produces a file selector
* dialog to save the game
*/
public Action getSaveGameAction() {
return saveGameAction;
}
/**
* @return an action adapter to set the target ticks per second
*/
public ActionAdapter getSetTargetTickPerSecondActions() {
return targetTicksPerSecondActions;
}
public int getTargetTicksPerSecond() {
ReadOnlyWorld world = modelRoot.getWorld();
return ((GameSpeed) world.get(ITEM.GAME_SPEED)).getSpeed();
}
public void propertyChange(Property p, Object oldValue, Object newValue) {
// switch (p) {
// case SAVED_GAMES_LIST:
// updateLoadGameAction();
// break;
//
// default:
// break;
// }
}
public void setup(ModelRootImpl modelRoot, DialogueBoxController dbc) {
this.modelRoot = modelRoot;
this.dbc = dbc;
modelRoot.addPropertyChangeListener(this);
}
public void setServerControlInterface() {
// Check that there is a file to load..
saveGameAction.setEnabled(true);
Enumeration<Action> e = targetTicksPerSecondActions.getActions();
targetTicksPerSecondActions.setPerformActionOnSetSelectedItem(false);
while (e.hasMoreElements()) {
e.nextElement().setEnabled(true);
}
String[] mapNames = NewGameMessage2Server.getMapNames();
Action[] actions = new Action[mapNames.length];
for (int j = 0; j < actions.length; j++) {
actions[j] = new NewGameAction(mapNames[j]);
actions[j].setEnabled(true);
}
selectMapActions = new ActionAdapter(actions);
newGameAction.setEnabled(true);
}
}

RHSJTabPane

Full name: jfreerails.client.view.RHSJTabPane

Documentation

/**
* The tabbed panel that sits in the lower right hand corner of the screen.
*
* @author rob
*/

Source Code

/**
* The tabbed panel that sits in the lower right hand corner of the screen.
*
* @author rob
*/
public class RHSJTabPane extends JTabbedPane implements ModelRootListener {
private static final long serialVersionUID = 3906926798502965297L;
private final TerrainInfoJPanel terrainInfoPanel;
private final StationInfoJPanel stationInfoPanel;
private final TrainListJPanel trainListPanel;
private final BuildTrackJPanel buildTrackPanel;
private ReadOnlyWorld world;
private int trainListIndex;
public RHSJTabPane() {
/*
* Dont accept keyboard focus since we want to leave it with the main
* map view.
*/
setFocusable(false);
ImageIcon trainListIcon;
ImageIcon buildTrackIcon;
/* set up trainsJTabbedPane */
setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
terrainInfoPanel = new TerrainInfoJPanel();
trainListPanel = new TrainListJPanel(true);
buildTrackPanel = new BuildTrackJPanel();
trainListPanel.removeButtons();
URL terrainInfoIconUrl = getClass().getResource(
"/jfreerails/client/graphics/icons/terrain_info.png");
ImageIcon terrainInfoIcon = new ImageIcon(terrainInfoIconUrl);
URL buildTrackIconUrl = getClass().getResource(
"/jfreerails/client/graphics/icons/track_new.png");
buildTrackIcon = new ImageIcon(buildTrackIconUrl);
URL trainListIconUrl = getClass().getResource(
"/jfreerails/client/graphics/icons/train_list.png");
trainListIcon = new ImageIcon(trainListIconUrl);
// Note titles set to null so only the icon appears at the top of the
// top.
JScrollPane terrainInfoJScrollPane = new JScrollPane(terrainInfoPanel);
terrainInfoJScrollPane
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
addTab(null, terrainInfoIcon, terrainInfoJScrollPane, "Terrain Info");
stationInfoPanel = new StationInfoJPanel();
stationInfoPanel.removeCloseButton();
// Don't show the station info tab until it has been rewritten to take
// up less space.
// JScrollPane stationInfoJScrollPane = new
// JScrollPane(stationInfoPanel);
// stationInfoJScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
// addTab(null, stationInfoIcon, stationInfoJScrollPane, "Station
// Info");
// this.stationInfoIndex= this.getTabCount()-1;
trainListPanel.setTrainViewHeight(20);
addTab(null, buildTrackIcon, buildTrackPanel, "Build Track");
addTab(null, trainListIcon, trainListPanel, "Train List");
this.trainListIndex = this.getTabCount() - 1;
/* These values were picked by trial and error! */
this.setMinimumSize(new Dimension(250, 200));
}
public void setup(final ActionRoot actionRoot, RenderersRoot vl,
final ModelRootImpl modelRoot) {
world = modelRoot.getWorld();
terrainInfoPanel.setup(world, vl);
stationInfoPanel.setup(modelRoot, vl, null);
ActionListener showTrain = new ActionListener() {
public void actionPerformed(ActionEvent e) {
int id = trainListPanel.getSelectedTrainID();
actionRoot.getDialogueBoxController().showTrainOrders(id);
}
};
trainListPanel.setShowTrainDetailsActionListener(showTrain);
trainListPanel.setup(modelRoot, vl, null);
modelRoot.addPropertyChangeListener(this);
buildTrackPanel.setup(modelRoot, actionRoot, vl, null);
}
/**
* Updates the Terrain Info Panel if the specified PropertyChangeEvent was
* triggered by the cursor moving.
*/
public void propertyChange(ModelRoot.Property prop, Object before,
Object after) {
if (prop.equals(ModelRoot.Property.CURSOR_POSITION)) {
ImPoint p = (ImPoint) after;
terrainInfoPanel.setTerrainType(((FreerailsTile) world.getTile(p.x,
p.y)).getTerrainTypeID());
}
}
public void setTrainTabEnabled(boolean enabled) {
this.setEnabledAt(this.trainListIndex, enabled);
}
public void setStationTabEnabled(boolean enabled) {
// this.setEnabledAt(this.stationInfoIndex, enabled);
}
}

TrainListCellRenderer

Full name: jfreerails.client.view.TrainListCellRenderer

Documentation

/**
* This JPanel displays an engine and a number of wagons.
*
* @author Luke Lindsay
*/

Source Code

/**
* This JPanel displays an engine and a number of wagons.
*
* @author Luke Lindsay
*/
public class TrainListCellRenderer extends JPanel implements View, ListCellRenderer,
WorldListListener {
private static final long serialVersionUID = 3546076964969591093L;
private ReadOnlyWorld w;
private RenderersRoot vl;
private int trainNumber = -1;
private int scheduleOrderNumber;
private int scheduleID = -1;
private int height = 100;
private FreerailsPrincipal principal;
private Image[] images = new Image[0];
/**
* Whether this JPanel should one of the trains orders from the schedule
* instead of the trains current formation.
*/
private boolean showingOrder = false;
/**
* If true, the train is drawn in the center to the JPanel; if false, the
* train is drawn left aligned.
*/
private boolean centerTrain = false;
private int trainWidth = 0;
private boolean selected = false;
private final Color backgroundColor = (java.awt.Color) javax.swing.UIManager.getDefaults().get(
"List.background");
private final Color selectedColor = (java.awt.Color) javax.swing.UIManager.getDefaults().get(
"List.selectionBackground");
private final Color selectedColorNotFocused = Color.LIGHT_GRAY;
public TrainListCellRenderer() {
this.setOpaque(false);
}
public TrainListCellRenderer(ModelRoot mr, RenderersRoot vl) {
setup(mr, vl, null);
this.setBackground(backgroundColor);
}
public void setCenterTrain(boolean b) {
this.centerTrain = b;
}
public void display(int newTrainNumber) {
showingOrder = false;
this.trainNumber = newTrainNumber;
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS, trainNumber);
display(train.getEngineType(), train.getConsist());
resetPreferredSize();
}
private void display(int engine, ImInts wagons){
images = new Image[1 + wagons.size()];
// images[0] = vl.getTrainImages().getSideOnEngineImage(
// train.getEngineType(), height);
String engineFilename = vl.getEngineImages(engine).sideOnFileName;
try {
images[0] = vl.getScaledImage(engineFilename, height);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException(engineFilename);
}
for (int i = 0; i < wagons.size(); i++) {
// images[i + 1] = vl.getTrainImages().getSideOnWagonImage(
// order.consist.get(i), height);
int wagonType = wagons.get(i);
String wagonFilename = vl.getWagonImages(wagonType).sideOnFileName;
try {
images[i + 1] = vl.getScaledImage(wagonFilename, height);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException(wagonFilename);
}
}
}
public void display(int newTrainNumber, int newScheduleOrderID) {
showingOrder = true;
this.trainNumber = newTrainNumber;
this.scheduleOrderNumber = newScheduleOrderID;
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS, trainNumber);
this.scheduleID = train.getScheduleID();
ImmutableSchedule s = (ImmutableSchedule) w.get(principal, KEY.TRAIN_SCHEDULES, scheduleID);
TrainOrdersModel order = s.getOrder(newScheduleOrderID);
// Set up the array of images.
if (null != order.consist) {
display(train.getEngineType(), order.consist);
} else {
images = new Image[0];
}
resetPreferredSize();
}
private void resetPreferredSize() {
int width = 0;
for (int i = 0; i < images.length; i++) {
width += images[i].getWidth(null);
}
this.trainWidth = width;
this.setPreferredSize(new Dimension(width, height));
}
public void setup(ModelRoot mr, RenderersRoot vl, Action closeAction) {
this.w = mr.getWorld();
this.vl = vl;
this.principal = mr.getPrincipal();
}
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
int trainID = NonNullElements.row2index(w, KEY.TRAINS, principal, index);
display(trainID);
selected = isSelected;
if (selected) {
if (list.isFocusOwner()) {
setBackground(selectedColor);
} else {
setBackground(selectedColorNotFocused);
}
} else {
setBackground(backgroundColor);
}
return this;
}
@Override
public int getHeight() {
return height;
}
public void setHeight(int i) {
height = i;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 0;
if (this.centerTrain) {
x = (this.getWidth() - this.trainWidth) / 2;
}
for (int i = 0; i < images.length; i++) {
g.drawImage(images[i], x, 0, null);
x += images[i].getWidth(null);
}
}
public void listUpdated(KEY key, int index, FreerailsPrincipal p) {
if (showingOrder) {
if (KEY.TRAIN_SCHEDULES == key && this.scheduleID == index) {
this.display(this.trainNumber, this.scheduleOrderNumber);
}
} else {
if (KEY.TRAINS == key && this.trainNumber == index) {
this.display(this.trainNumber);
}
}
}
public void itemAdded(KEY key, int index, FreerailsPrincipal p) {
}
public void itemRemoved(KEY key, int index, FreerailsPrincipal p) {
}
}

DisplayModesComboBoxModels

Full name: jfreerails.client.view.DisplayModesComboBoxModels

Documentation

/**
* ComboBoxModel that provides access to the screen resolutions and bit depths
* available.
*
* @author Luke Lindsay
*/

Source Code

/**
* ComboBoxModel that provides access to the screen resolutions and bit depths
* available.
*
* @author Luke Lindsay
*/
public class DisplayModesComboBoxModels implements javax.swing.ComboBoxModel {
private final GraphicsConfiguration defaultConfiguration = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
private final ArrayList<MyDisplayMode> modes = new ArrayList<MyDisplayMode>();
private MyDisplayMode selection;
public DisplayModesComboBoxModels() {
DisplayMode currentMode = defaultConfiguration.getDevice()
.getDisplayMode();
selection = new MyDisplayMode(currentMode);
DisplayMode[] displayModes = defaultConfiguration.getDevice()
.getDisplayModes();
for (int i = 0; i < displayModes.length; i++) {
MyDisplayMode mode = new MyDisplayMode(displayModes[i]);
modes.add(mode);
}
}
/**
* Permanently removes from the list in this object any display modes with
* width, height, or bitdepth below the specified values.
*/
public void removeDisplayModesBelow(int width, int height, int bitdepth) {
Iterator<MyDisplayMode> it = modes.iterator();
while (it.hasNext()) {
MyDisplayMode mode = it.next();
DisplayMode displayMode = mode.displayMode;
final boolean tooNarrow = displayMode.getWidth() < width;
final boolean tooShort = displayMode.getHeight() < height;
/*
* Note, displayMode.getBitDepth() may return
* DisplayMode.BIT_DEPTH_MULTI, which is -1.
*/
final boolean tooFewColours = (displayMode.getBitDepth() < bitdepth)
&& (displayMode.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI);
if (tooNarrow || tooShort || tooFewColours) {
it.remove();
}
}
}
public Object getSelectedItem() {
return selection;
}
public void setSelectedItem(Object anItem) {
selection = (MyDisplayMode) anItem;
}
public void addListDataListener(javax.swing.event.ListDataListener l) {
}
public MyDisplayMode getElementAt(int index) {
return modes.get(index);
}
public int getSize() {
return modes.size();
}
public void removeListDataListener(javax.swing.event.ListDataListener l) {
}
}

NewsPaperJPanel

Full name: jfreerails.client.view.NewsPaperJPanel

Documentation

/**
* A JPanel that displays a newspaper headline.
*
* @author lindsal8
*
*/

Source Code

/**
* A JPanel that displays a newspaper headline.
*
* @author lindsal8
*
*/
public class NewsPaperJPanel extends javax.swing.JPanel implements View {
private static final long serialVersionUID = 3258410638366946868L;
private final GraphicsConfiguration defaultConfiguration = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
private ActionListener callBack;
private final Image pieceOfNewspaper;
public NewsPaperJPanel() {
initComponents();
Image tempImage = (new javax.swing.ImageIcon(getClass().getResource(
"/jfreerails/data/newspaper.png"))).getImage();
pieceOfNewspaper = defaultConfiguration.createCompatibleImage(tempImage
.getWidth(null), tempImage.getHeight(null),
Transparency.BITMASK);
Graphics g = pieceOfNewspaper.getGraphics();
g.drawImage(tempImage, 0, 0, null);
this.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mousePressed(java.awt.event.MouseEvent evt) {
callBack.actionPerformed(new ActionEvent(this, 0, null));
}
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() { // GEN-BEGIN:initComponents
headline = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
anyKeyToContinueJLabel = new javax.swing.JLabel();
setLayout(null);
setPreferredSize(new java.awt.Dimension(640, 400));
setMinimumSize(new java.awt.Dimension(640, 400));
setMaximumSize(new java.awt.Dimension(640, 400));
setOpaque(false);
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
headline.setPreferredSize(new java.awt.Dimension(620, 110));
headline.setMinimumSize(new java.awt.Dimension(620, 110));
headline.setText("NEWSPAPER HEADLINE");
headline.setForeground(java.awt.Color.black);
headline.setBackground(java.awt.Color.white);
headline.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
headline.setFont(new java.awt.Font("Lucida Bright", 1, 36));
headline.setMaximumSize(new java.awt.Dimension(620, 110));
add(headline);
headline.setBounds(10, 70, 620, 110);
jPanel1.setBorder(new javax.swing.border.BevelBorder(0));
anyKeyToContinueJLabel.setText("Click to continue");
anyKeyToContinueJLabel.setForeground(java.awt.Color.black);
anyKeyToContinueJLabel.setBackground(java.awt.Color.darkGray);
jPanel1.add(anyKeyToContinueJLabel);
add(jPanel1);
jPanel1.setBounds(230, 260, 190, 30);
}
// GEN-END:initComponents
private void formKeyPressed(java.awt.event.KeyEvent evt) { // GEN-FIRST:event_formKeyPressed
// Add your handling code here:
this.setVerifyInputWhenFocusTarget(false);
}
// GEN-LAST:event_formKeyPressed
@Override
public void paint(Graphics g) {
g.drawImage(this.pieceOfNewspaper, 0, 0, null);
this.paintChildren(g);
}
public void setHeadline(String s) {
this.headline.setText(s);
}
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
this.callBack = closeAction;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel headline;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel anyKeyToContinueJLabel;
// End of variables declaration//GEN-END:variables
}

TrainDescriptionJPanel

Full name: jfreerails.client.view.TrainDescriptionJPanel

Documentation

/**
* This JPanel displays a side-on view of a train and a summary of the cargo
* that it is carrying.
*
* @author Luke Lindsay
*/

Source Code

/**
* This JPanel displays a side-on view of a train and a summary of the cargo
* that it is carrying.
*
* @author Luke Lindsay
*/
public class TrainDescriptionJPanel extends javax.swing.JPanel implements View{
private static final long serialVersionUID = 3977018444325664049L;
private ReadOnlyWorld w;
private FreerailsPrincipal principal;
private int trainNumber = -1;
private FreerailsSerializable lastTrain, lastCargoBundle;
public TrainDescriptionJPanel() {
initComponents();
}
@Override
protected void paintComponent(Graphics arg0) {
//Check whether the train or its cargo have changed since the last call to this method.
updateIfNecessary();
super.paintComponent(arg0);
}
private void updateIfNecessary() {
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
trainNumber);
for (int i = 0; i < train.getNumberOfWagons(); i++) {
// this.sideOnTrainViewJPanel1.addWagon(train.getWagon(i));
}
int cargoBundleID = train.getCargoBundleID();
FreerailsSerializable cb = w.get(
principal, KEY.CARGO_BUNDLES, cargoBundleID);
if(train != lastTrain || cb != lastCargoBundle)
displayTrain(trainNumber);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jLabel1 = new javax.swing.JLabel();
trainViewJPanel1 = new jfreerails.client.view.TrainListCellRenderer();
setLayout(new java.awt.GridBagLayout());
setBorder(new javax.swing.border.TitledBorder("Current Details"));
setPreferredSize(new java.awt.Dimension(250, 97));
jLabel1.setFont(new java.awt.Font("Dialog", 0, 12));
jLabel1
.setText("<html><head></head><body>Trains X: 20 passengers, 15 tons of mfg goods, 12 sacks of mail, and 7 tons of livestock.</body></html>");
jLabel1.setMinimumSize(new java.awt.Dimension(250, 17));
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
jLabel1.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jLabel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
add(trainViewJPanel1, gridBagConstraints);
}// GEN-END:initComponents
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
this.trainViewJPanel1.setup(mr, vl, closeAction);
trainViewJPanel1.setHeight(30);
trainViewJPanel1.setCenterTrain(true);
this.w = mr.getWorld();
principal = mr.getPrincipal();
}
public void displayTrain(int newTrainNumber) {
NonNullElements it = new NonNullElements(KEY.TRAINS, w, principal);
it.gotoIndex(newTrainNumber);
this.trainNumber = newTrainNumber;
trainViewJPanel1.display(newTrainNumber);
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
newTrainNumber);
for (int i = 0; i < train.getNumberOfWagons(); i++) {
// this.sideOnTrainViewJPanel1.addWagon(train.getWagon(i));
}
int cargoBundleID = train.getCargoBundleID();
ImmutableCargoBundle cb = (ImmutableCargoBundle) w.get(
principal, KEY.CARGO_BUNDLES, cargoBundleID);
String s = "Train #" + it.getNaturalNumber() + ": ";
int numberOfTypesInBundle = 0;
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
int amount = cb.getAmount(i);
if (0 != amount) {
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, i);
String cargoTypeName = ct.getDisplayName();
if (0 != numberOfTypesInBundle) {
s += "; ";
}
numberOfTypesInBundle++;
s += cargoTypeName + " (" + amount + ")";
}
}
if (0 == numberOfTypesInBundle) {
s += "no cargo";
}
s += ".";
this.jLabel1.setText(s);
this.lastCargoBundle = cb;
this.lastTrain = train;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private jfreerails.client.view.TrainListCellRenderer trainViewJPanel1;
// End of variables declaration//GEN-END:variables
}

CashJLabel

Full name: jfreerails.client.view.CashJLabel

Documentation

/**
* This JLabel shows the amount of cash available.
*
* @author Luke
*
*/

Source Code

/**
* This JLabel shows the amount of cash available.
*
* @author Luke
*
*/
public class CashJLabel extends JLabel implements View {
private static final long serialVersionUID = 3257853181542412341L;
private ReadOnlyWorld w;
private FreerailsPrincipal principal;
public CashJLabel() {
this.setText(" ");
}
public void setup(ModelRoot model, RenderersRoot vl,
Action closeAction) {
this.w = model.getWorld();
principal = model.getPrincipal();
}
@Override
protected void paintComponent(Graphics g) {
if (null != w) {
Money m = w.getCurrentBalance(principal);
String s = m.toString();
this.setText("$" + s);
}
super.paintComponent(g);
}
}

StationPlacementCursor

Full name: jfreerails.client.view.StationPlacementCursor

Documentation

/**
* This class implements a cursor which can be used to place a station on the
* map. Mode of operation:
* <ol>
* <li>User selects a station to place, which sets the current cursor to the
* station placement cursor.
* <li>User highlights desired build location with the mouse, boundary of the
* station radius is highlighted. If the station cannot be built, the boundary
* highlights in red.
* <li>User places station with the left mouse button.
* <li>User may cancel placement by using the right mouse button
* <li>Cursor fires the actionPerformed causing the station to be built.
* </ol>
* When the StationBuildAction is no longer enabled, the owner reverts to the
* regular cursor type. TODO scroll the area when the mouse hovers at the edge
* of the map.
*
* @author rob
*/

Source Code

/**
* This class implements a cursor which can be used to place a station on the
* map. Mode of operation:
* <ol>
* <li>User selects a station to place, which sets the current cursor to the
* station placement cursor.
* <li>User highlights desired build location with the mouse, boundary of the
* station radius is highlighted. If the station cannot be built, the boundary
* highlights in red.
* <li>User places station with the left mouse button.
* <li>User may cancel placement by using the right mouse button
* <li>Cursor fires the actionPerformed causing the station to be built.
* </ol>
* When the StationBuildAction is no longer enabled, the owner reverts to the
* regular cursor type. TODO scroll the area when the mouse hovers at the edge
* of the map.
*
* @author rob
*/
public class StationPlacementCursor extends MouseInputAdapter {
public static void wireUp(ActionRoot actionRoot, StationRadiusRenderer srr,
MapViewJComponent mapView) {
StationPlacementCursor spc = new StationPlacementCursor(actionRoot,
srr, mapView);
spc.init();
}
private final PropertyChangeListener buildActionListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if (e.getPropertyName().equals(
StationBuildModel.StationBuildAction.STATION_POSITION_KEY)) {
/* update the renderer pos */
Point p = (Point) e.getNewValue();
stationRadiusRenderer.setPosition(p.x, p.y);
if (stationBuildModel.canBuildStationHere()) {
stationRadiusRenderer
.setBorderColor(StationRadiusRenderer.COLOR_OK);
} else {
stationRadiusRenderer
.setBorderColor(StationRadiusRenderer.COLOR_CANNOT_BUILD);
}
} else if (e.getPropertyName().equals(
StationBuildModel.StationBuildAction.STATION_RADIUS_KEY)) {
Integer radius = (Integer) e.getNewValue();
stationRadiusRenderer.setRadius(radius.intValue());
}
boolean enabled = stationBuildModel.getStationBuildAction()
.isEnabled();
if (buildEnabled != enabled) {
if (enabled) {
mapView.addMouseListener(StationPlacementCursor.this);
mapView.addMouseMotionListener(StationPlacementCursor.this);
stationRadiusRenderer.show();
} else {
stationRadiusRenderer.hide();
mapView.removeMouseListener(StationPlacementCursor.this);
mapView
.removeMouseMotionListener(StationPlacementCursor.this);
}
buildEnabled = enabled;
}
}
};
private boolean buildEnabled;
private final MapViewJComponent mapView;
private final float scale;
private final StationBuildModel stationBuildModel;
private final StationRadiusRenderer stationRadiusRenderer;
private StationPlacementCursor(ActionRoot actionRoot,
StationRadiusRenderer srr, MapViewJComponent mapView) {
scale = mapView.getScale();
this.mapView = mapView;
stationBuildModel = actionRoot.getStationBuildModel();
stationRadiusRenderer = srr;
buildEnabled = stationBuildModel.getStationBuildAction().isEnabled();
}
private void init() {
if (buildEnabled) {
mapView.addMouseListener(this);
mapView.addMouseMotionListener(this);
stationRadiusRenderer.show();
} else {
stationRadiusRenderer.hide();
mapView.removeMouseListener(this);
mapView.removeMouseMotionListener(this);
}
stationBuildModel.getStationBuildAction().addPropertyChangeListener(
buildActionListener);
}
@Override
public void mouseClicked(MouseEvent e) {
int button = e.getButton();
if (button == MouseEvent.BUTTON1) {
/* attempt to build */
stationBuildModel.getStationBuildAction().actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""));
} else if (button == MouseEvent.BUTTON3) {
/* cancel the build */
stationBuildModel.getStationCancelAction().actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""));
}
}
@Override
public void mouseEntered(MouseEvent e) {
stationRadiusRenderer.show();
}
@Override
public void mouseExited(MouseEvent e) {
stationRadiusRenderer.hide();
}
@Override
public void mouseMoved(MouseEvent e) {
if (stationBuildModel.isPositionFollowsMouse()) {
Point p = e.getPoint();
Point mapCoord = new Point((int) (p.x / scale), (int) (p.y / scale));
stationBuildModel.getStationBuildAction().putValue(
StationBuildModel.StationBuildAction.STATION_POSITION_KEY,
mapCoord);
}
}
}

LoadGameJPanel

Full name: jfreerails.client.view.LoadGameJPanel

Documentation

/**
*
* @author Luke
*/

Source Code

/**
*
* @author Luke
*/
public class LoadGameJPanel extends javax.swing.JPanel implements View {
private static final long serialVersionUID = -6810248272441137826L;
private ImStringList lastFiles;
/** Creates new form LoadGameJPanel */
public LoadGameJPanel() {
initComponents();
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jLabel1 = new javax.swing.JLabel();
okButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
refreshButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jScrollPane1.setViewportView(jList1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(jScrollPane1, gridBagConstraints);
jLabel1.setText("Please select a game to load.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(jLabel1, gridBagConstraints);
okButton.setText("OK");
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(okButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(cancelButton, gridBagConstraints);
refreshButton.setText("Refresh");
refreshButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
refreshButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(refreshButton, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents
private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
Message2Server refreshGames = new RefreshListOfGamesMessage2Server(2);
modelRoot.sendCommand(refreshGames);
}//GEN-LAST:event_refreshButtonActionPerformed
private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
}//GEN-LAST:event_formComponentShown
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
if(null != close)
close.actionPerformed(evt);
}//GEN-LAST:event_cancelButtonActionPerformed
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
String filename = (String)jList1.getSelectedValue();
Message2Server message2 = new LoadGameMessage2Server(1,
filename);
modelRoot.sendCommand(message2);
if(null != close)
close.actionPerformed(evt);
}//GEN-LAST:event_okButtonActionPerformed
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged
okButton.setEnabled(jList1.getSelectedIndex() != -1);
}//GEN-LAST:event_jList1ValueChanged
public void setup(ModelRoot m, RenderersRoot vl, Action closeAction) {
this.close = closeAction;
modelRoot = m;
updateListOfFiles();
}
private void updateListOfFiles() {
ImStringList files = (ImStringList) modelRoot.getProperty(Property.SAVED_GAMES_LIST);
Object[] saves = new Object[files.size()];
for (int i = 0; i < files.size(); i++) {
saves[i] = files.get(i);
}
jList1.setListData(saves);
okButton.setEnabled(jList1.getSelectedIndex() != -1);
lastFiles = files;
}
@Override
protected void paintComponent(Graphics g) {
ImStringList files = (ImStringList) modelRoot.getProperty(Property.SAVED_GAMES_LIST);
if(!lastFiles.equals(files)){
updateListOfFiles();
}
super.paintComponent(g);
}
ModelRoot modelRoot;
ActionListener close;
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JButton cancelButton;
javax.swing.JLabel jLabel1;
javax.swing.JList jList1;
javax.swing.JScrollPane jScrollPane1;
javax.swing.JButton okButton;
javax.swing.JButton refreshButton;
// End of variables declaration//GEN-END:variables
}

TrainScheduleJPanel

Full name: jfreerails.client.view.TrainScheduleJPanel

Documentation

/**
* This JPanel displays a train's schedule and provides controls that let you
* edit it.
*
* @author Luke Lindsay
*/

Source Code

/**
* This JPanel displays a train's schedule and provides controls that let you
* edit it.
*
* @author Luke Lindsay
*/
public class TrainScheduleJPanel extends javax.swing.JPanel implements View,
WorldListListener {
private static final long serialVersionUID = 3762248626113884214L;
private static final Logger logger = Logger
.getLogger(TrainScheduleJPanel.class.getName());
private int trainNumber = -1;
private int scheduleID = -1;
private TrainOrdersListModel listModel;
private ModelRoot modelRoot;
private RenderersRoot vl;
public TrainScheduleJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
trainOrderJPanel1 = new jfreerails.client.view.TrainOrderJPanel();
editOrderJPopupMenu = new javax.swing.JPopupMenu();
gotoStationJMenuItem = new javax.swing.JMenuItem();
changeStation = new javax.swing.JMenuItem();
removeStationJMenuItem = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JSeparator();
addWagonJMenu = new javax.swing.JMenu();
removeWagonsJMenu = new javax.swing.JMenu();
removeLastJMenuItem = new javax.swing.JMenuItem();
removeAllJMenuItem = new javax.swing.JMenuItem();
changeConsistJMenu = new javax.swing.JMenu();
noChangeJMenuItem = new javax.swing.JMenuItem();
engineOnlyJMenuItem = new javax.swing.JMenuItem();
autoConsistJMenuItem = new javax.swing.JMenuItem();
waitJMenu = new javax.swing.JMenu();
dontWaitJMenuItem = new javax.swing.JMenuItem();
waitUntilFullJMenuItem = new javax.swing.JMenuItem();
jSeparator2 = new javax.swing.JSeparator();
pullUpJMenuItem = new javax.swing.JMenuItem();
pushDownJMenuItem = new javax.swing.JMenuItem();
selectStationJPanel1 = new jfreerails.client.view.SelectStationJPanel();
selectStationJPopupMenu = new javax.swing.JPopupMenu();
this.selectStationJPopupMenu.add(selectStationJPanel1);
addStationJButton = new javax.swing.JButton();
priorityOrdersJButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
orders = new javax.swing.JList();
gotoStationJMenuItem.setText("Goto station");
gotoStationJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
gotoStationJMenuItemActionPerformed(evt);
}
});
editOrderJPopupMenu.add(gotoStationJMenuItem);
changeStation.setText("Change Station");
changeStation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
changeStationActionPerformed(evt);
}
});
editOrderJPopupMenu.add(changeStation);
removeStationJMenuItem.setText("Remove station");
removeStationJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeStationJMenuItemActionPerformed(evt);
}
});
editOrderJPopupMenu.add(removeStationJMenuItem);
editOrderJPopupMenu.add(jSeparator1);
addWagonJMenu.setText("Add Wagon");
editOrderJPopupMenu.add(addWagonJMenu);
removeWagonsJMenu.setText("Remove wagon(s)");
removeLastJMenuItem.setText("Remove last");
removeLastJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeLastJMenuItemActionPerformed(evt);
}
});
removeWagonsJMenu.add(removeLastJMenuItem);
removeAllJMenuItem.setText("Remove all wagons");
removeAllJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeAllJMenuItemActionPerformed(evt);
}
});
removeWagonsJMenu.add(removeAllJMenuItem);
editOrderJPopupMenu.add(removeWagonsJMenu);
changeConsistJMenu.setText("Change consist to..");
noChangeJMenuItem.setText("'No change'");
noChangeJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
noChangeJMenuItemActionPerformed(evt);
}
});
changeConsistJMenu.add(noChangeJMenuItem);
engineOnlyJMenuItem.setText("Engine only");
engineOnlyJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
engineOnlyJMenuItemActionPerformed(evt);
}
});
changeConsistJMenu.add(engineOnlyJMenuItem);
autoConsistJMenuItem.setText("Choose wagons automatically");
autoConsistJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
autoConsistJMenuItemActionPerformed(evt);
}
});
changeConsistJMenu.add(autoConsistJMenuItem);
editOrderJPopupMenu.add(changeConsistJMenu);
waitJMenu.setText("Wait at station");
dontWaitJMenuItem.setText("Don't wait");
dontWaitJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dontWaitJMenuItemActionPerformed(evt);
}
});
waitJMenu.add(dontWaitJMenuItem);
waitUntilFullJMenuItem.setText("Wait until full");
waitUntilFullJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
waitUntilFullJMenuItemActionPerformed(evt);
}
});
waitJMenu.add(waitUntilFullJMenuItem);
editOrderJPopupMenu.add(waitJMenu);
editOrderJPopupMenu.add(jSeparator2);
pullUpJMenuItem.setText("Pull up");
pullUpJMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pullUpJMenuItemActionPerformed(evt);
}
});
editOrderJPopupMenu.add(pullUpJMenuItem);
pushDownJMenuItem.setText("Push down");
pushDownJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pushDownJMenuItemActionPerformed(evt);
}
});
editOrderJPopupMenu.add(pushDownJMenuItem);
setLayout(new java.awt.GridBagLayout());
setBorder(new javax.swing.border.TitledBorder("Schedule"));
addStationJButton.setText("Add Station");
addStationJButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addStationJButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(addStationJButton, gridBagConstraints);
priorityOrdersJButton.setText("Add Priority Orders");
priorityOrdersJButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
priorityOrdersJButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(priorityOrdersJButton, gridBagConstraints);
jScrollPane1.setPreferredSize(new java.awt.Dimension(280, 160));
orders
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
orders.setCellRenderer(trainOrderJPanel1);
orders.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
ordersKeyPressed(evt);
}
});
orders.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
ordersMouseClicked(evt);
}
});
jScrollPane1.setViewportView(orders);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
add(jScrollPane1, gridBagConstraints);
}// GEN-END:initComponents
private void ordersKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_ordersKeyPressed
switch (evt.getKeyCode()) {
case KeyEvent.VK_O: {
// Add priority orders
priorityOrdersJButtonActionPerformed(null);
break;
}
case KeyEvent.VK_N: {
// Add station
addStationJButtonActionPerformed(null);
break;
}
default: {
// do nothing.
}
}
int orderNumber = this.orders.getSelectedIndex();
if (orderNumber == -1) {
// No order is selected.
return;
}
switch (evt.getKeyCode()) {
case KeyEvent.VK_G: {
// Goto station.
gotoStationJMenuItemActionPerformed(null);
break;
}
case KeyEvent.VK_S: {
// Change station
showSelectStation(this.getSchedule(), orderNumber);
break;
}
case KeyEvent.VK_A: {
// Auto schedule
setAutoConsist();
break;
}
case KeyEvent.VK_C: {
// Change add wagon
break;
}
case KeyEvent.VK_DELETE: {
// Remove station
removeStationJMenuItemActionPerformed(null);
break;
}
case KeyEvent.VK_BACK_SPACE: {
// Remove last wagon
removeLastWagon();
break;
}
case KeyEvent.VK_W: {
// toggle wait until full
MutableSchedule s = getSchedule();
TrainOrdersModel order = s.getOrder(orderNumber);
setWaitUntilFull(!order.waitUntilFull);
break;
}
default: {
// do nothing.
}
}
listModel.fireRefresh();
}// GEN-LAST:event_ordersKeyPressed
private void autoConsistJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_autoConsistJMenuItemActionPerformed
setAutoConsist();
}// GEN-LAST:event_autoConsistJMenuItemActionPerformed
private void changeStationActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_changeStationActionPerformed
int orderNumber = this.orders.getSelectedIndex();
showSelectStation(this.getSchedule(), orderNumber);
}// GEN-LAST:event_changeStationActionPerformed
private void removeAllJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_removeAllJMenuItemActionPerformed
removeAllWagons();
}// GEN-LAST:event_removeAllJMenuItemActionPerformed
private void removeLastJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_removeLastJMenuItemActionPerformed
removeLastWagon();
}// GEN-LAST:event_removeLastJMenuItemActionPerformed
private void waitUntilFullJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_waitUntilFullJMenuItemActionPerformed
setWaitUntilFull(true);
}// GEN-LAST:event_waitUntilFullJMenuItemActionPerformed
private void dontWaitJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_dontWaitJMenuItemActionPerformed
setWaitUntilFull(false);
}// GEN-LAST:event_dontWaitJMenuItemActionPerformed
private void engineOnlyJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_engineOnlyJMenuItemActionPerformed
removeAllWagons();
}// GEN-LAST:event_engineOnlyJMenuItemActionPerformed
private void noChangeJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_noChangeJMenuItemActionPerformed
noChange();
}// GEN-LAST:event_noChangeJMenuItemActionPerformed
private void priorityOrdersJButtonActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_priorityOrdersJButtonActionPerformed
MutableSchedule s = getSchedule();
try {
s.setPriorityOrders(new TrainOrdersModel(getFirstStationID(), null,
false, false));// TODO fix bug
showSelectStation(s, Schedule.PRIORITY_ORDERS);
} catch (NoSuchElementException e) {
logger
.warning("No stations exist so can't add station to schedule!");
}
}// GEN-LAST:event_priorityOrdersJButtonActionPerformed
private void addStationJButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addStationJButtonActionPerformed
MutableSchedule s = getSchedule();
try {
int newOrderNumber = s.addOrder(new TrainOrdersModel(
getFirstStationID(), null, false, false)); // TODO fix bug
showSelectStation(s, newOrderNumber);
} catch (NoSuchElementException e) {
logger
.warning("No stations exist so can't add station to schedule!");
}
}// GEN-LAST:event_addStationJButtonActionPerformed
private void removeStationJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_removeStationJMenuItemActionPerformed
MutableSchedule s = getSchedule();
if(s.getNumOrders() ==0){
logger.warning("Can't remove orders since non exist!");
return;
}
int i = orders.getSelectedIndex();
if(s.getNumOrders() <= i){
logger.warning("Order #"+String.valueOf(i)+" does not exist!");
return;
}
s.removeOrder(i);
sendUpdateMove(s);
}// GEN-LAST:event_removeStationJMenuItemActionPerformed
private void gotoStationJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_gotoStationJMenuItemActionPerformed
MutableSchedule s = getSchedule();
int i = orders.getSelectedIndex();
s.setOrderToGoto(i);
sendUpdateMove(s);
}// GEN-LAST:event_gotoStationJMenuItemActionPerformed
private void pushDownJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pushDownJMenuItemActionPerformed
MutableSchedule s = getSchedule();
int i = orders.getSelectedIndex();
s.pushDown(i);
sendUpdateMove(s);
orders.setSelectedIndex(i + 1);
}// GEN-LAST:event_pushDownJMenuItemActionPerformed
private void ordersMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_ordersMouseClicked
int i = orders.getSelectedIndex();
MutableSchedule s = getSchedule();
if (i >= s.getNumOrders()) {
// The selected index does not exist!
// For some reason, the JList hasn't updated yet.
i = -1;
}
if (-1 != i && java.awt.event.MouseEvent.BUTTON3 == evt.getButton()) {
// If an element is select and the right button is pressed.
TrainOrdersModel order = s.getOrder(i);
pullUpJMenuItem.setEnabled(s.canPullUp(i));
pushDownJMenuItem.setEnabled(s.canPushDown(i));
gotoStationJMenuItem.setEnabled(s.canSetGotoStation(i));
removeWagonsJMenu.setEnabled(order.orderHasWagons());
waitJMenu.setEnabled(order.orderHasWagons());
addWagonJMenu.setEnabled(order.hasLessThanMaximumNumberOfWagons());
setupWagonsPopup();
this.editOrderJPopupMenu.show(evt.getComponent(), evt.getX(), evt
.getY());
}
}// GEN-LAST:event_ordersMouseClicked
private void pullUpJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pullUpJMenuItemActionPerformed
MutableSchedule s = getSchedule();
int i = orders.getSelectedIndex();
s.pullUp(i);
sendUpdateMove(s);
orders.setSelectedIndex(i - 1);
}// GEN-LAST:event_pullUpJMenuItemActionPerformed
public void setup(ModelRoot mr, RenderersRoot vl, Action al) {
trainOrderJPanel1.setup(mr, vl, null);
this.modelRoot = mr;
this.vl = vl;
// This actionListener is fired by the select station popup when a
// station is selected.
Action action = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent evt) {
sendUpdateMove(selectStationJPanel1.generateNewSchedule());
selectStationJPopupMenu.setVisible(false);
listModel.fireRefresh();
orders.requestFocus();
}
};
this.selectStationJPanel1.setup(mr, vl, action);
}
public void display(int newTrainNumber) {
this.trainNumber = newTrainNumber;
FreerailsPrincipal principal = modelRoot.getPrincipal();
ReadOnlyWorld w = modelRoot.getWorld();
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
newTrainNumber);
this.scheduleID = train.getScheduleID();
listModel = new TrainOrdersListModel(w, newTrainNumber, principal);
orders.setModel(listModel);
orders.setFixedCellWidth(250);
listModel.fireRefresh();
enableButtons();
}
private void enableButtons() {
MutableSchedule s = getSchedule();
addStationJButton.setEnabled(s.canAddOrder());
// Only one set of priority orders are allowed.
priorityOrdersJButton.setEnabled(!s.hasPriorityOrders());
}
private MutableSchedule getSchedule() {
FreerailsPrincipal principal = modelRoot.getPrincipal();
ReadOnlyWorld w = modelRoot.getWorld();
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
trainNumber);
ImmutableSchedule immutableSchedule = (ImmutableSchedule) w.get(
principal, KEY.TRAIN_SCHEDULES, train.getScheduleID());
return new MutableSchedule(immutableSchedule);
}
/**
* Since stations can be removed, we should not assume that station 0
* exists: this method returns the id of the first station that exists.
*
*/
private int getFirstStationID() {
NonNullElements stations = new NonNullElements(KEY.STATIONS, modelRoot
.getWorld(), modelRoot.getPrincipal());
if (stations.next()) {
return stations.getIndex();
}
throw new NoSuchElementException();
}
private void setupWagonsPopup() {
addWagonJMenu.removeAll(); // Remove existing menu items.
NonNullElements cargoTypes = new NonNullElements(SKEY.CARGO_TYPES,
modelRoot.getWorld());
while (cargoTypes.next()) {
final CargoType wagonType = (CargoType) cargoTypes.getElement();
JMenuItem wagonMenuItem = new JMenuItem();
final int wagonTypeNumber = cargoTypes.getIndex();
wagonMenuItem.setText(wagonType.getDisplayName());
Image image = vl.getWagonImages(wagonTypeNumber).getSideOnImage();
int height = image.getHeight(null);
int width = image.getWidth(null);
int scale = height / 10;
ImageIcon icon = new ImageIcon(image.getScaledInstance(width
/ scale, height / scale, Image.SCALE_FAST));
wagonMenuItem.setIcon(icon);
wagonMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
addWagon(wagonTypeNumber);
}
});
addWagonJMenu.add(wagonMenuItem);
}
}
private void noChange() {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
newOrders = new TrainOrdersModel(oldOrders.getStationID(), null, false,
false);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
private void setWaitUntilFull(boolean b) {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
// If auto-consist is set do nothing
if (oldOrders.autoConsist)
return;
// If no-change is set do nothing
if (oldOrders.consist == null)
return;
boolean autoConsist = false;
newOrders = new TrainOrdersModel(oldOrders.getStationID(),
oldOrders.consist, b, autoConsist);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
private void setAutoConsist() {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
newOrders = new TrainOrdersModel(oldOrders.getStationID(), null, false,
true);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
private void addWagon(int wagonTypeNumber) {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
int[] newConsist;
// The consist will be null if old orders were 'no change'.
if (null != oldOrders.consist) {
int oldLength = oldOrders.consist.size();
newConsist = new int[oldLength + 1];
// Copy existing wagons
for (int i = 0; i < oldLength; i++) {
newConsist[i] = oldOrders.consist.get(i);
}
// Then add specified wagon.
newConsist[oldLength] = wagonTypeNumber;
} else {
newConsist = new int[] { wagonTypeNumber };
}
newOrders = new TrainOrdersModel(oldOrders.getStationID(), new ImInts(
newConsist), oldOrders.getWaitUntilFull(), false);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
private void removeAllWagons() {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
newOrders = new TrainOrdersModel(oldOrders.getStationID(),
new ImInts(), false, false);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
private void removeLastWagon() {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
ImInts oldConsist = oldOrders.consist;
if( null == oldConsist){
//consist can be null if there is no
//scheduled change of wagons.
//Fixes freerails bug 1687677 and freerails2 bug 2014234
return;
}
int newLength = oldConsist.size() - 1;
if (newLength < 0) {
//No wagons to remove!
return;
}
ImInts newConsist = oldConsist.removeLast();
newOrders = new TrainOrdersModel(oldOrders.getStationID(), newConsist,
oldOrders.waitUntilFull, false);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}
private void sendUpdateMove(MutableSchedule mutableSchedule) {
FreerailsPrincipal principal = modelRoot.getPrincipal();
ReadOnlyWorld w = modelRoot.getWorld();
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
this.trainNumber);
// int scheduleID = train.getScheduleID();
assert (scheduleID == train.getScheduleID());
ImmutableSchedule before = (ImmutableSchedule) w.get(
principal, KEY.TRAIN_SCHEDULES, scheduleID);
ImmutableSchedule after = mutableSchedule.toImmutableSchedule();
Move m = new ChangeTrainScheduleMove(scheduleID, before, after,
principal);
this.modelRoot.doMove(m);
}
public void listUpdated(KEY key, int index, FreerailsPrincipal p) {
if (KEY.TRAIN_SCHEDULES == key && this.scheduleID == index) {
listModel.fireRefresh();
enableButtons();
}
}
public void itemAdded(KEY key, int index, FreerailsPrincipal p) {
// do nothing.
}
public void itemRemoved(KEY key, int index, FreerailsPrincipal p) {
// do nothing.
}
/**
* Show the popup that lets the user select a station, called when a new
* scheduled stop is added and when an existing scheduled stop is changed.
*/
private void showSelectStation(MutableSchedule schedule, int orderNumber) {
selectStationJPanel1.display(schedule, orderNumber);
// Show the select station popup in the middle of the window.
Container topLevelAncestor = this.getTopLevelAncestor();
Dimension d = topLevelAncestor.getSize();
Dimension d2 = selectStationJPopupMenu.getPreferredSize();
int x = Math.max((d.width - d2.width) / 2, 0);
int y = Math.max((d.height - d2.height) / 2, 0);
selectStationJPopupMenu.show(topLevelAncestor, x, y);
selectStationJPanel1.requestFocus();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JButton addStationJButton;
javax.swing.JMenu addWagonJMenu;
javax.swing.JMenuItem autoConsistJMenuItem;
javax.swing.JMenu changeConsistJMenu;
javax.swing.JMenuItem changeStation;
javax.swing.JMenuItem dontWaitJMenuItem;
javax.swing.JPopupMenu editOrderJPopupMenu;
javax.swing.JMenuItem engineOnlyJMenuItem;
javax.swing.JMenuItem gotoStationJMenuItem;
javax.swing.JScrollPane jScrollPane1;
javax.swing.JSeparator jSeparator1;
javax.swing.JSeparator jSeparator2;
javax.swing.JMenuItem noChangeJMenuItem;
javax.swing.JList orders;
javax.swing.JButton priorityOrdersJButton;
javax.swing.JMenuItem pullUpJMenuItem;
javax.swing.JMenuItem pushDownJMenuItem;
javax.swing.JMenuItem removeAllJMenuItem;
javax.swing.JMenuItem removeLastJMenuItem;
javax.swing.JMenuItem removeStationJMenuItem;
javax.swing.JMenu removeWagonsJMenu;
jfreerails.client.view.SelectStationJPanel selectStationJPanel1;
javax.swing.JPopupMenu selectStationJPopupMenu;
jfreerails.client.view.TrainOrderJPanel trainOrderJPanel1;
javax.swing.JMenu waitJMenu;
javax.swing.JMenuItem waitUntilFullJMenuItem;
// End of variables declaration//GEN-END:variables
}

View

Full name: jfreerails.client.view.View

Documentation

/**
* Defines a standard method to initiate GUI components that need access to the
* ModelRoot.
*
* @author Luke
*
*/

Source Code

/**
* Defines a standard method to initiate GUI components that need access to the
* ModelRoot.
*
* @author Luke
*
*/
public interface View {
void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction);
}

Methods

MainMapAndOverviewMapMediator

Full name: jfreerails.client.view.MainMapAndOverviewMapMediator

Documentation

/**
* This class mediates between the main map view and the overview map view. It
* does the following:<br>
* (1) Updates the rectangle on the overview map when the visible rectangle of
* the main map changes.<br>
* (2) Updates the main map visible rectangle when the user clicks on the
* overview map.<br>
* (3) Updates the main map visible rectangle when the user drags the rectangle
* on the overview map.<br>
* (4) Changes the mouse cursor to indicate that the rectangle on the overview
* map is draggable when the mouse moves into the rectangle.
*
* @author Luke Lindsay
* @version 1.0
*/

Source Code

/**
* This class mediates between the main map view and the overview map view. It
* does the following:<br>
* (1) Updates the rectangle on the overview map when the visible rectangle of
* the main map changes.<br>
* (2) Updates the main map visible rectangle when the user clicks on the
* overview map.<br>
* (3) Updates the main map visible rectangle when the user drags the rectangle
* on the overview map.<br>
* (4) Changes the mouse cursor to indicate that the rectangle on the overview
* map is draggable when the mouse moves into the rectangle.
*
* @author Luke Lindsay
* @version 1.0
*/
public class MainMapAndOverviewMapMediator extends MouseInputAdapter {
private JComponent overviewMapJPanel;
private JViewport viewport;
private JComponent mainMap;
private Rectangle currentVisRect;
private Point lastMouseLocation = new Point();
private boolean inside = false;
private boolean draggingAndStartedInside = false;
public MainMapAndOverviewMapMediator() {
}
public MainMapAndOverviewMapMediator(JComponent omv, JViewport v,
JComponent mm, Rectangle rect) {
setup(omv, v, mm, rect);
}
public void setup(JComponent omv, JViewport v, JComponent mm, Rectangle rect) {
currentVisRect = rect;
overviewMapJPanel = omv;
viewport = v;
mainMap = mm;
overviewMapJPanel.addMouseMotionListener(this);
overviewMapJPanel.addMouseListener(this);
viewport.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(ChangeEvent e) {
updateObservedRect();
}
});
overviewMapJPanel
.addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(
java.awt.event.ComponentEvent evt) {
updateObservedRect();
}
@Override
public void componentShown(java.awt.event.ComponentEvent evt) {
updateObservedRect();
}
});
}
@Override
public void mouseMoved(MouseEvent evt) {
lastMouseLocation.x = evt.getX();
lastMouseLocation.y = evt.getY();
updateInside(evt);
}
@Override
public void mousePressed(MouseEvent evt) {
if (inside) {
draggingAndStartedInside = true;
}
}
@Override
public void mouseReleased(MouseEvent evt) {
draggingAndStartedInside = false;
}
@Override
public void mouseDragged(MouseEvent evt) {
if (draggingAndStartedInside) {
/*
* Rectangle r= overviewMapJPanel.mainMapVisibleRect;
* r.x+=evt.getX()-lastMouseLocation.x;
* r.y+=evt.getY()-lastMouseLocation.y;
* lastMouseLocation.x=evt.getX(); lastMouseLocation.y=evt.getY();
*
* updateInside(evt); overviewMapJPanel.repaint();
*/
int deltaX = evt.getX() - lastMouseLocation.x;
int deltaY = evt.getY() - lastMouseLocation.y;
lastMouseLocation.x = evt.getX();
lastMouseLocation.y = evt.getY();
// float overviewScale=overviewMapJPanel.getScale();
// float mainMapScale=mainMap.getScale();
int overviewScale = overviewMapJPanel.getPreferredSize().width;
int mainMapScale = mainMap.getWidth();
int scaledDeltaX = (deltaX * mainMapScale / overviewScale);
int scaledDeltaY = (deltaY * mainMapScale / overviewScale);
Rectangle r = mainMap.getVisibleRect();
r.x += scaledDeltaX;
r.y += scaledDeltaY;
mainMap.scrollRectToVisible(r);
updateInside(evt);
}
}
@Override
public void mouseClicked(MouseEvent evt) {
/*
* Rectangle r= overviewMapJPanel.mainMapVisibleRect;
* r.x=evt.getX()-r.width/2; r.y=evt.getY()-r.width/2;
*/
// float overviewScale=overviewMapJPanel.getScale();
// float mainMapScale=mainMap.getScale();
int overviewScale = overviewMapJPanel.getPreferredSize().width;
int mainMapScale = mainMap.getWidth();
int x = (evt.getX() * mainMapScale / overviewScale);
int y = (evt.getY() * mainMapScale / overviewScale);
Rectangle r = mainMap.getVisibleRect();
r.x = x - r.width / 2;
r.y = y - r.height / 2;
mainMap.scrollRectToVisible(r);
updateInside(evt);
}
private void updateInside(MouseEvent evt) {
// Rectangle r= overviewMapJPanel.mainMapVisibleRect;
boolean b = currentVisRect.contains(evt.getX(), evt.getY());
if (b != inside) {
inside = b;
if (inside) {
overviewMapJPanel.setCursor(new Cursor(Cursor.MOVE_CURSOR));
} else {
overviewMapJPanel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
}
private void updateObservedRect() {
Rectangle r = mainMap.getVisibleRect();
// if (!r.equals(this.currentVisRect)) {
// float overviewScale=overviewMapJPanel.getScale();
// float mainMapScale=mainMap.getScale();
int overviewScale = overviewMapJPanel.getPreferredSize().width;
int mainMapScale = mainMap.getWidth();
if (0 != (overviewScale * mainMapScale)) {
// avoid division by zero.
currentVisRect.x = (r.x * overviewScale / mainMapScale);
currentVisRect.y = (r.y * overviewScale / mainMapScale);
currentVisRect.width = (r.width * overviewScale / mainMapScale);
currentVisRect.height = (r.height * overviewScale / mainMapScale);
overviewMapJPanel.repaint();
}
// }
}
}

IncomeStatementHtmlJPanel

Full name: jfreerails.client.view.IncomeStatementHtmlJPanel

Documentation

/**
* A HtmlJPanel that displays the income statement.
*
* @author Luke
*
*/

Source Code

/**
* A HtmlJPanel that displays the income statement.
*
* @author Luke
*
*/
public class IncomeStatementHtmlJPanel extends HtmlJPanel implements View {
private static final long serialVersionUID = 3257846588885120057L;
private String template;
private int lastNumTransactions = 0;
private ModelRoot modelRoot;
public IncomeStatementHtmlJPanel() {
super();
URL url = IncomeStatementHtmlJPanel.class
.getResource("/jfreerails/client/view/income_statement.htm");
template = loadText(url);
}
@Override
public void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
super.setup(modelRoot, vl, closeAction);
this.modelRoot = modelRoot;
updateHtml();
}
private void updateHtml() {
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
IncomeStatementGenerator balanceSheetGenerator = new IncomeStatementGenerator(
world, playerPrincipal);
String populatedTemplate = populateTokens(template,
balanceSheetGenerator);
setHtml(populatedTemplate);
}
@Override
protected void paintComponent(Graphics g) {
/* Check to see if the text needs updating before painting. */
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
int currentNumberOfTransactions = world
.getNumberOfTransactions(playerPrincipal);
if (currentNumberOfTransactions != lastNumTransactions) {
updateHtml();
}
super.paintComponent(g);
}
}

TrainDialogueJPanel

Full name: jfreerails.client.view.TrainDialogueJPanel

Documentation

/**
* JPanel that displays info on a train; it is composed of a
* {@link TrainScheduleJPanel} and {@link TrainDescriptionJPanel}.
*
* @author Luke Lindsay
*/

Source Code

/**
* JPanel that displays info on a train; it is composed of a
* {@link TrainScheduleJPanel} and {@link TrainDescriptionJPanel}.
*
* @author Luke Lindsay
*/
public class TrainDialogueJPanel extends javax.swing.JPanel implements View,
WorldListListener {
private static final long serialVersionUID = 3257005466801157938L;
private static final Logger logger = Logger
.getLogger(TrainDialogueJPanel.class.getName());
private WorldIterator wi;
private ReadOnlyWorld w;
private FreerailsPrincipal principal;
public TrainDialogueJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
newTrainScheduleJPanel1 = new jfreerails.client.view.TrainScheduleJPanel();
trainDetailsJPanel1 = new TrainDescriptionJPanel();
previousJButton = new javax.swing.JButton();
nextJButton = new javax.swing.JButton();
trainListJButton = new javax.swing.JButton();
closeJButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(510, 400));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(newTrainScheduleJPanel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
add(trainDetailsJPanel1, gridBagConstraints);
previousJButton.setText("last");
previousJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
previousJButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(previousJButton, gridBagConstraints);
nextJButton.setText("next");
nextJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextJButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(nextJButton, gridBagConstraints);
trainListJButton.setText("Train list");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(trainListJButton, gridBagConstraints);
closeJButton.setText("Close");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(closeJButton, gridBagConstraints);
}// GEN-END:initComponents
private void previousJButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_previousJButtonActionPerformed
// Add your handling code here:
if (wi.previous()) {
display(wi.getIndex());
} else {
logger.warning("Couldn't get previous");
}
}// GEN-LAST:event_previousJButtonActionPerformed
private void nextJButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_nextJButtonActionPerformed
// Add your handling code here:
if (wi.next()) {
display(wi.getIndex());
} else {
logger.warning("Couldn't get next");
}
}// GEN-LAST:event_nextJButtonActionPerformed
public void setup(ModelRoot mr, RenderersRoot vl, Action al) {
newTrainScheduleJPanel1.setup(mr, vl, al);
trainDetailsJPanel1.setup(mr, vl, al);
this.setCancelButtonActionListener(al);
this.principal = mr.getPrincipal();
this.w = mr.getWorld();
}
public void display(int trainNumber) {
wi = new NonNullElements(KEY.TRAINS, w, principal);
wi.gotoIndex(trainNumber);
if (wi.getRowID() > 0) {
this.previousJButton.setEnabled(true);
} else {
this.previousJButton.setEnabled(false);
}
if (wi.getRowID() < (wi.size() - 1)) {
this.nextJButton.setEnabled(true);
} else {
this.nextJButton.setEnabled(false);
}
newTrainScheduleJPanel1.display(trainNumber);
trainDetailsJPanel1.displayTrain(trainNumber);
}
public void listUpdated(KEY key, int index, FreerailsPrincipal p) {
newTrainScheduleJPanel1.listUpdated(key, index, p);
}
public void itemAdded(KEY key, int index, FreerailsPrincipal p) {
}
public void itemRemoved(KEY key, int index, FreerailsPrincipal p) {
}
void setTrainDetailsButtonActionListener(ActionListener l) {
ActionListener[] oldListeners = trainListJButton.getActionListeners();
for (int i = 0; i < oldListeners.length; i++) {
trainListJButton.removeActionListener(oldListeners[i]);
}
this.trainListJButton.addActionListener(l);
}
/**
* Removes any existing ActionListener listeners from the cancel button,
* then adds the specified one.
*/
void setCancelButtonActionListener(ActionListener l) {
ActionListener[] oldListeners = closeJButton.getActionListeners();
for (int i = 0; i < oldListeners.length; i++) {
closeJButton.removeActionListener(oldListeners[i]);
}
this.closeJButton.addActionListener(l);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JButton closeJButton;
jfreerails.client.view.TrainScheduleJPanel newTrainScheduleJPanel1;
javax.swing.JButton nextJButton;
javax.swing.JButton previousJButton;
jfreerails.client.view.TrainDescriptionJPanel trainDetailsJPanel1;
javax.swing.JButton trainListJButton;
// End of variables declaration//GEN-END:variables
}

OverHeadTrainView

Full name: jfreerails.client.view.OverHeadTrainView

Documentation

/**
* Draws the trains on the main map.
*
* @author Luke
*/

Source Code

/**
* Draws the trains on the main map.
*
* @author Luke
*/
public class OverHeadTrainView implements Painter {
private final TrainRenderer trainRenderer;
private final ReadOnlyWorld w;
private SoundManager soundManager = SoundManager.getSoundManager();
private ModelRoot mr;
public OverHeadTrainView(ReadOnlyWorld world, RenderersRoot rr, ModelRoot mr) {
this.w = world;
trainRenderer = new TrainRenderer(rr);
this.mr = mr;
}
public TrainRenderer getTrainRenderer() {
return trainRenderer;
}
public void paint(Graphics2D g) {
g.setColor(Color.BLUE);
g.setStroke(new BasicStroke(10));
Double time = (Double)mr.getProperty(Property.TIME);
for (int k = 0; k < w.getNumberOfPlayers(); k++) {
FreerailsPrincipal principal = w.getPlayer(k).getPrincipal();
int selectedTrain = -1;
if (mr.getPrincipal().getWorldIndex() == principal.getWorldIndex()) {
//These are our trains...
Object property = mr.getProperty(Property.SELECTED_TRAIN);
if (null != property) {
selectedTrain = (Integer) property;
}
}
for (int i = 0; i < w.size(principal, KEY.TRAINS); i++) {
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS, i);
// TrainPositionOnMap pos = (TrainPositionOnMap) w.get(
// principal, KEY.TRAIN_POSITIONS, i);
TrainAccessor ta = new TrainAccessor(w, principal, i);
TrainPositionOnMap pos = ta.findPosition(time);
if (pos.isCrashSite()
&& (pos.getFrameCt() <= TrainPositionOnMap.CRASH_FRAMES_COUNT)) {
trainRenderer.paintTrainCrash(g, pos);
if (pos.getFrameCt() == 1) {
try {
soundManager.playSound(
"/jfreerails/client/sounds/traincrash.wav",
1);
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
TrainImages.Highlight highlight = i == selectedTrain ? TrainImages.Highlight.SELECTED: null;
trainRenderer.paintTrain(g, train, pos, highlight);
}
}
}
}
}

TrainOrderJPanel

Full name: jfreerails.client.view.TrainOrderJPanel

Documentation

/**
* ListCellRenderer that displays a train order.
*
* @author Luke Lindsay
*/

Source Code

/**
* ListCellRenderer that displays a train order.
*
* @author Luke Lindsay
*/
public class TrainOrderJPanel extends javax.swing.JPanel implements View,
ListCellRenderer {
private static final long serialVersionUID = 4051047466990319413L;
private jfreerails.world.top.ReadOnlyWorld w;
private FreerailsPrincipal principal;
private final ImageIcon gotoNow = new ImageIcon(TrainOrderJPanel.class
.getResource("/jfreerails/client/graphics/selected_arrow.png"));
private final ImageIcon gotoAfterPriorityOrders = new ImageIcon(
TrainOrderJPanel.class
.getResource("/jfreerails/client/graphics/deselected_arrow.png"));
private final ImageIcon dontGoto = null;
private final Color backgroundColor = (java.awt.Color) javax.swing.UIManager
.getDefaults().get("List.background");
private final Color selectedColor = (java.awt.Color) javax.swing.UIManager
.getDefaults().get("List.selectionBackground");
private final Color selectedColorNotFocused = Color.LIGHT_GRAY;
public TrainOrderJPanel() {
initComponents();
this.setBackground(backgroundColor);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
gotoIcon = new javax.swing.JLabel();
consistChangeJPanel = new TrainListCellRenderer();
noChangeJLabel = new javax.swing.JLabel();
stationNameJLabel = new javax.swing.JLabel();
ordersJLabel = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
gotoIcon.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/jfreerails/client/graphics/selected_arrow.png")));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
add(gotoIcon, gridBagConstraints);
consistChangeJPanel.setLayout(new java.awt.GridBagLayout());
noChangeJLabel.setText("No Change");
consistChangeJPanel.add(noChangeJLabel,
new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
add(consistChangeJPanel, gridBagConstraints);
stationNameJLabel.setText("Some Station");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
add(stationNameJLabel, gridBagConstraints);
ordersJLabel.setText("wait until full / don't wait");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.ipadx = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 5);
add(ordersJLabel, gridBagConstraints);
}// GEN-END:initComponents
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
this.w = mr.getWorld();
TrainListCellRenderer trainViewJPanel = (TrainListCellRenderer) consistChangeJPanel;
trainViewJPanel.setHeight(15);
trainViewJPanel.setup(mr, vl, null);
this.principal = mr.getPrincipal();
}
public java.awt.Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus) {
TrainOrdersListModel.TrainOrdersListElement trainOrders = (TrainOrdersListModel.TrainOrdersListElement) value;
// Set station name
int stationNumber = trainOrders.order.stationId;
StationModel station = (StationModel) w.get(principal,
KEY.STATIONS, stationNumber);
String stationName = station.getStationName();
this.stationNameJLabel.setText(stationName);
// Set wait until full
String waitUntilFull = trainOrders.order.waitUntilFull ? "Wait until full"
: "";
this.ordersJLabel.setText(waitUntilFull);
// Set selected
if (isSelected) {
if (list.isFocusOwner()) {
setBackground(selectedColor);
} else {
setBackground(selectedColorNotFocused);
}
} else {
setBackground(backgroundColor);
}
// Set goto status.
switch (trainOrders.gotoStatus) {
case TrainOrdersListModel.DONT_GOTO:
this.gotoIcon.setIcon(this.dontGoto);
break;
case TrainOrdersListModel.GOTO_AFTER_PRIORITY_ORDERS:
this.gotoIcon.setIcon(this.gotoAfterPriorityOrders);
break;
case TrainOrdersListModel.GOTO_NOW:
this.gotoIcon.setIcon(this.gotoNow);
break;
default:
throw new IllegalArgumentException(String
.valueOf(trainOrders.gotoStatus));
}
this.gotoIcon.setPreferredSize(new Dimension(20, 20));
// Set consist
TrainListCellRenderer trainViewJPanel = (TrainListCellRenderer) consistChangeJPanel;
trainViewJPanel.display(trainOrders.trainNumber, index);
// Show priority orders.
if (trainOrders.isPriorityOrder) {
// Write the station name in upper case
String s = this.stationNameJLabel.getText();
this.stationNameJLabel.setText(s + " (Priority Orders)");
}
// Check for 'No change'
if (null == trainOrders.order.consist) {
if (trainOrders.order.autoConsist) {
this.noChangeJLabel.setText("Select wagons automatically");
} else {
this.noChangeJLabel.setText("No Change");
}
} else {
this.noChangeJLabel.setText(null);
}
// Set the section title
// this.sectionTitleJLabel.setText("trainOrders.sectionTitle");
return this;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JPanel consistChangeJPanel;
javax.swing.JLabel gotoIcon;
javax.swing.JLabel noChangeJLabel;
javax.swing.JLabel ordersJLabel;
javax.swing.JLabel stationNameJLabel;
// End of variables declaration//GEN-END:variables
}

DetailMapRenderer

Full name: jfreerails.client.view.DetailMapRenderer

Documentation

/**
* Draws the main map, that is the terrain, track, trains, station names etc.
*
* @author Luke
*/

Source Code

/**
* Draws the main map, that is the terrain, track, trains, station names etc.
*
* @author Luke
*/
public class DetailMapRenderer implements MapRenderer {
private static final boolean OSXWorkaround = (System
.getProperty("OSXWorkaround") != null);
private final MapLayerRenderer background;
private final Dimension mapSizeInPixels;
private final OverHeadTrainView trainsview;
private final StationRadiusRenderer stationRadius;
private final BuildTrackRenderer buildTrackRenderer;
private final BuildTrackController buildTrackController;
private final Painter stationBoxes;
public DetailMapRenderer(ReadOnlyWorld world, RenderersRoot rr,
ModelRoot modelRoot) {
trainsview = new OverHeadTrainView(world, rr, modelRoot);
MapBackgroundRender render = new MapBackgroundRender(world, rr,
modelRoot);
if (OSXWorkaround) {
// Don't buffer the mapviews background.
background = render;
} else {
background = new SquareTileBackgroundRenderer(render);
}
Dimension mapSize = new Dimension(world.getMapWidth(), world
.getMapHeight());
mapSizeInPixels = new Dimension(mapSize.width * Constants.TILE_SIZE,
mapSize.height * Constants.TILE_SIZE);
stationRadius = new StationRadiusRenderer(modelRoot);
buildTrackRenderer = new BuildTrackRenderer(rr, modelRoot);
buildTrackController = new BuildTrackController(world, modelRoot);
stationBoxes = new StationBoxRenderer(world, rr, modelRoot);
}
public StationRadiusRenderer getStationRadius() {
return stationRadius;
}
public BuildTrackController getBuildTrackController() {
return buildTrackController;
}
public float getScale() {
return Constants.TILE_SIZE;
}
public Dimension getMapSizeInPixels() {
return mapSizeInPixels;
}
public TrainRenderer getTrainRenderer() {
return this.trainsview.getTrainRenderer();
}
public void paintTile(Graphics g, int tileX, int tileY) {
background.paintTile(g, tileX, tileY);
trainsview.paint((Graphics2D) g);
stationRadius.paint((Graphics2D) g);
stationBoxes.paint((Graphics2D) g);
buildTrackRenderer.paint((Graphics2D) g);
}
public void refreshTile(int x, int y) {
background.refreshTile(x, y);
}
public void paintRect(Graphics g, Rectangle visibleRect) {
background.paintRect(g, visibleRect);
trainsview.paint((Graphics2D) g);
stationRadius.paint((Graphics2D) g);
stationBoxes.paint((Graphics2D) g);
buildTrackRenderer.paint((Graphics2D) g);
}
public void refreshAll() {
background.refreshAll();
}
}

IncomeStatementGenerator

Full name: jfreerails.client.view.IncomeStatementGenerator

Documentation

/**
* Generates the income statement- note, its fields are read using reflection so
* don't change their names.
*
* @author Luke
*
*/

Source Code

/**
* Generates the income statement- note, its fields are read using reflection so
* don't change their names.
*
* @author Luke
*
*/
public class IncomeStatementGenerator {
GameTime from;
GameTime to;
final ReadOnlyWorld w;
final FreerailsPrincipal principal;
private int startyear = 0;
private GameCalendar cal;
public Money mailTotal;
public Money passengersTotal;
public Money fastFreightTotal;
public Money slowFreightTotal;
public Money bulkFreightTotal;
public Money interestTotal;
public Money trainMaintenanceTotal;
public Money trackMaintenanceTotal;
public Money stationMaintenanceTotal;
public Money profitTotal;
public Money mailYtd;
public Money passengersYtd;
public Money fastFreightYtd;
public Money slowFreightYtd;
public Money bulkFreightYtd;
public Money interestYtd;
public Money trainMaintenanceYtd;
public Money trackMaintenanceYtd;
public Money stationMaintenanceYtd;
public Money profitYtd;
public String year;
IncomeStatementGenerator(ReadOnlyWorld w, FreerailsPrincipal principal) {
this.w = w;
this.principal = principal;
cal = (GameCalendar) w.get(ITEM.CALENDAR);
// Income from cargo delivery
mailTotal = calRevenue(Categories.Mail);
passengersTotal = calRevenue(Categories.Passengers);
fastFreightTotal = calRevenue(Categories.Fast_Freight);
slowFreightTotal = calRevenue(Categories.Slow_Freight);
bulkFreightTotal = calRevenue(Categories.Bulk_Freight);
// Expenses.
interestTotal = calTotal(INTEREST_CHARGE);
trainMaintenanceTotal = calTotal(TRAIN_MAINTENANCE);
trackMaintenanceTotal = calTotal(TRACK_MAINTENANCE);
stationMaintenanceTotal = calTotal(STATION_MAINTENANCE);
/*
* Note, expenses are stored as negative values so we just add
* everything up.
*/
long profit = mailTotal.getAmount() + passengersTotal.getAmount()
+ fastFreightTotal.getAmount() + slowFreightTotal.getAmount()
+ bulkFreightTotal.getAmount() + interestTotal.getAmount()
+ trainMaintenanceTotal.getAmount()
+ trackMaintenanceTotal.getAmount()
+ stationMaintenanceTotal.getAmount();
profitTotal = new Money(profit);
GameTime time = w.currentTime();
startyear = cal.getYear(time.getTicks());
year = String.valueOf(startyear);
// Income from cargo delivery
mailYtd = calRevenue(Categories.Mail);
passengersYtd = calRevenue(Categories.Passengers);
fastFreightYtd = calRevenue(Categories.Fast_Freight);
slowFreightYtd = calRevenue(Categories.Slow_Freight);
bulkFreightYtd = calRevenue(Categories.Bulk_Freight);
// Expenses.
interestYtd = calTotal(INTEREST_CHARGE);
trainMaintenanceYtd = calTotal(TRAIN_MAINTENANCE);
trackMaintenanceYtd = calTotal(TRACK_MAINTENANCE);
stationMaintenanceYtd = calTotal(STATION_MAINTENANCE);
/*
* Note, expenses are stored as negative values so we just add
* everything up.
*/
profit = mailYtd.getAmount() + passengersYtd.getAmount()
+ fastFreightYtd.getAmount() + slowFreightYtd.getAmount()
+ bulkFreightYtd.getAmount() + interestYtd.getAmount()
+ trainMaintenanceYtd.getAmount()
+ trackMaintenanceYtd.getAmount()
+ stationMaintenanceYtd.getAmount();
profitYtd = new Money(profit);
}
/** Calculates the total revenue from the specified cargo type. */
Money calRevenue(Categories cargoCategory) {
long amount = 0;
for (int i = 0; i < w.getNumberOfTransactions(this.principal); i++) {
Transaction t = w.getTransaction(principal, i);
GameTime time = w.getTransactionTimeStamp(principal, i);
if (t instanceof DeliverCargoReceipt
&& cal.getYear(time.getTicks()) >= this.startyear) {
DeliverCargoReceipt dcr = (DeliverCargoReceipt) t;
int cargoType = dcr.getCb().getCargoType();
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, cargoType);
if (ct.getCategory().equals(cargoCategory)) {
amount += dcr.deltaCash().getAmount();
}
}
}
return new Money(amount);
}
Money calTrainRevenue(int trainId) {
long amount = 0;
for (int i = 0; i < w.getNumberOfTransactions(this.principal); i++) {
Transaction t = w.getTransaction(principal, i);
GameTime time = w.getTransactionTimeStamp(principal, i);
if (t instanceof DeliverCargoReceipt
&& cal.getYear(time.getTicks()) >= this.startyear) {
DeliverCargoReceipt dcr = (DeliverCargoReceipt) t;
if (dcr.getTrainId() == trainId) {
amount += dcr.deltaCash().getAmount();
}
}
}
return new Money(amount);
}
private Money calTotal(Transaction.Category transactionCategory) {
long amount = 0;
for (int i = 0; i < w.getNumberOfTransactions(this.principal); i++) {
Transaction t = w.getTransaction(principal, i);
GameTime time = w.getTransactionTimeStamp(principal, i);
if (t.getCategory() == transactionCategory
&& cal.getYear(time.getTicks()) >= this.startyear) {
amount += t.deltaCash().getAmount();
}
}
return new Money(amount);
}
}

BuildTrackJPanel

Full name: jfreerails.client.view.BuildTrackJPanel

Documentation

/**
* A JPanel that presents toggle buttons that let the player select the build
* mode (build track, upgrade track, build station, bulldoze, and info mode) and
* select the track/bridge/station type to use.
*
* @author Luke
*/

Source Code

/**
* A JPanel that presents toggle buttons that let the player select the build
* mode (build track, upgrade track, build station, bulldoze, and info mode) and
* select the track/bridge/station type to use.
*
* @author Luke
*/
public class BuildTrackJPanel extends javax.swing.JPanel implements ActiveView {
private static final long serialVersionUID = 3618701915647850036L;
private final ImageManager imageManager = new ImageManagerImpl(
"/jfreerails/client/graphics/");
private HashMap<TrackRule.TrackCategories, Integer> selectionSet;
private ModelRoot modelRoot;
private TrackMoveProducer trackMoveProducer;
private StationBuildModel stationBuildModel;
/** Creates new form BuildTrackJPanel */
public BuildTrackJPanel() {
initComponents();
}
public void setup(ModelRoot mr, ActionRoot ar, RenderersRoot vl,
ActionListener al) {
modelRoot = mr;
stationBuildModel = ar.getStationBuildModel();
trackMoveProducer = ar.getTrackMoveProducer();
if (null == trackMoveProducer)
throw new NullPointerException();
selectionSet = new HashMap<TrackRule.TrackCategories, Integer>();
trackButtonGroup = new javax.swing.ButtonGroup();
bridgeButtonGroup = new javax.swing.ButtonGroup();
stationButtonGroup = new javax.swing.ButtonGroup();
tunnelButtonGroup = new javax.swing.ButtonGroup();
// Remove any existing buttons.
bridgesJPanel.removeAll();
stationsJPanel.removeAll();
trackJPanel.removeAll();
tunnelsJPanel.removeAll();
// Add the new set of buttons.
ReadOnlyWorld world = mr.getWorld();
for (int i = 0; i < world.size(SKEY.TRACK_RULES); i++) {
JToggleButton toggleButton = new JToggleButton();
final Integer ruleID = new Integer(i);
TrackRule rule = (TrackRule) world.get(SKEY.TRACK_RULES, i);
TrackRule.TrackCategories category = rule.getCategory();
Money price = null;
switch (category) {
case track:
trackButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon(rule.getTypeName()));
toggleButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
selectionSet
.put(TrackRule.TrackCategories.track,
ruleID);
setBuildTrackStrategy();
}
});
price = rule.getPrice();
trackJPanel.add(toggleButton);
break;
case bridge:
bridgeButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon(rule.getTypeName()));
toggleButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
selectionSet.put(
TrackRule.TrackCategories.bridge,
ruleID);
setBuildTrackStrategy();
}
});
bridgesJPanel.add(toggleButton);
price = rule.getFixedCost();
break;
case tunnel:
tunnelButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon(rule.getTypeName()));
toggleButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
selectionSet.put(
TrackRule.TrackCategories.tunnel,
ruleID);
setBuildTrackStrategy();
}
});
price = rule.getPrice();
tunnelsJPanel.add(toggleButton);
break;
case station:
stationButtonGroup.add(toggleButton);
toggleButton.setAction(stationBuildModel
.getStationChooseAction(ruleID));
toggleButton.setIcon(getIcon(rule.getTypeName()));
toggleButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
selectionSet.put(
TrackRule.TrackCategories.station,
ruleID);
}
});
stationsJPanel.add(toggleButton);
price = rule.getFixedCost();
break;
}
toggleButton.setPreferredSize(new java.awt.Dimension(36, 36));
String tooltip = Utils.capitalizeEveryWord(rule.getTypeName())
+ " $" + price.toString();
toggleButton.setToolTipText(tooltip);
if (!selectionSet.containsKey(category)) {
selectionSet.put(category, new Integer(i));
toggleButton.setSelected(true);
}
}
addNoTunnelsButton();
addNoBridgesButton();
// Default to add track.
addTrackActionPerformed(null);
buildModeButtonGroup.setSelected(addTrack.getModel(), true);
setBuildTrackStrategy();
// Make the buttons non-focusable
setFocusableFalse(bridgeButtonGroup);
setFocusableFalse(trackButtonGroup);
setFocusableFalse(tunnelButtonGroup);
setFocusableFalse(stationButtonGroup);
setFocusableFalse(buildModeButtonGroup);
// Add button click
// buildTrackJPanel.addKeyListener(new KeyListener(){
// public void keyPressed(KeyEvent e){
// System.out.println(e.getKeyCode());
// viewMode.doClick();
// }
// public void keyReleased(KeyEvent e){
//
// }
// public void keyTyped(KeyEvent e){
//
// }
// });
}
/** Calls setFocusable(false) for each button in the button group. */
private void setFocusableFalse(ButtonGroup bg) {
for (Enumeration<AbstractButton> buttons = bg.getElements(); buttons
.hasMoreElements();) {
buttons.nextElement().setFocusable(false);
}
}
private void addNoTunnelsButton() {
JToggleButton toggleButton = new JToggleButton();
tunnelButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon("no_tunnels"));
toggleButton.setPreferredSize(new java.awt.Dimension(36, 36));
toggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectionSet.put(TrackRule.TrackCategories.tunnel, null);
setBuildTrackStrategy();
}
});
toggleButton.setToolTipText("Don't build tunnels");
tunnelsJPanel.add(toggleButton);
}
private void addNoBridgesButton() {
JToggleButton toggleButton = new JToggleButton();
bridgeButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon("no_bridges"));
toggleButton.setPreferredSize(new java.awt.Dimension(36, 36));
toggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectionSet.put(TrackRule.TrackCategories.bridge, null);
setBuildTrackStrategy();
}
});
toggleButton.setToolTipText("Don't build bridges");
bridgesJPanel.add(toggleButton);
}
private ImageIcon getIcon(String typeName) {
try {
String relativeFileName = "icons" + File.separator + typeName
+ ".png";
relativeFileName = relativeFileName.replace(' ', '_');
Image im = imageManager.getImage(relativeFileName);
return new ImageIcon(im);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException(e);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
buildModeButtonGroup = new javax.swing.ButtonGroup();
trackButtonGroup = new javax.swing.ButtonGroup();
bridgeButtonGroup = new javax.swing.ButtonGroup();
stationButtonGroup = new javax.swing.ButtonGroup();
tunnelButtonGroup = new javax.swing.ButtonGroup();
buildModeJPanel = new javax.swing.JPanel();
addTrack = new javax.swing.JToggleButton();
upgradeTrack = new javax.swing.JToggleButton();
addStation = new javax.swing.JToggleButton();
bulldoze = new javax.swing.JToggleButton();
viewMode = new javax.swing.JToggleButton();
trackJPanel = new javax.swing.JPanel();
viewMode1 = new javax.swing.JToggleButton();
bridgesJPanel = new javax.swing.JPanel();
viewMode2 = new javax.swing.JToggleButton();
tunnelsJPanel = new javax.swing.JPanel();
viewMode3 = new javax.swing.JToggleButton();
stationsJPanel = new javax.swing.JPanel();
viewMode4 = new javax.swing.JToggleButton();
spacer = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
setFocusable(false);
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
@Override
public void keyTyped(java.awt.event.KeyEvent evt) {
formKeyTyped(evt);
}
});
buildModeJPanel.setLayout(new java.awt.FlowLayout(
java.awt.FlowLayout.LEFT, 4, 2));
buildModeButtonGroup.add(addTrack);
addTrack.setIcon(getIcon("build track"));
addTrack.setSelected(true);
addTrack.setToolTipText("Build Track");
addTrack.setFocusable(false);
addTrack.setPreferredSize(new java.awt.Dimension(36, 36));
addTrack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addTrackActionPerformed(evt);
}
});
buildModeJPanel.add(addTrack);
buildModeButtonGroup.add(upgradeTrack);
upgradeTrack.setIcon(getIcon("upgrade track"));
upgradeTrack.setToolTipText("Upgrade Track");
upgradeTrack.setFocusable(false);
upgradeTrack.setPreferredSize(new java.awt.Dimension(36, 36));
upgradeTrack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
upgradeTrackActionPerformed(evt);
}
});
buildModeJPanel.add(upgradeTrack);
buildModeButtonGroup.add(addStation);
addStation.setIcon(getIcon("build stations"));
addStation.setToolTipText("Build Station");
addStation.setFocusable(false);
addStation.setPreferredSize(new java.awt.Dimension(36, 36));
addStation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addStationActionPerformed(evt);
}
});
buildModeJPanel.add(addStation);
buildModeButtonGroup.add(bulldoze);
bulldoze.setIcon(getIcon("bulldozer"));
bulldoze.setToolTipText("Remove Track");
bulldoze.setFocusable(false);
bulldoze.setPreferredSize(new java.awt.Dimension(36, 36));
bulldoze.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bulldozeActionPerformed(evt);
}
});
buildModeJPanel.add(bulldoze);
buildModeButtonGroup.add(viewMode);
viewMode.setIcon(getIcon("eye"));
viewMode.setToolTipText("Don't build anything");
viewMode.setFocusable(false);
viewMode.setPreferredSize(new java.awt.Dimension(36, 36));
viewMode.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewModeActionPerformed(evt);
}
});
buildModeJPanel.add(viewMode);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(buildModeJPanel, gridBagConstraints);
trackJPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT,
4, 2));
buildModeButtonGroup.add(viewMode1);
viewMode1.setIcon(getIcon("turn_off"));
viewMode1.setPreferredSize(new java.awt.Dimension(36, 36));
trackJPanel.add(viewMode1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(trackJPanel, gridBagConstraints);
bridgesJPanel.setLayout(new java.awt.FlowLayout(
java.awt.FlowLayout.LEFT, 4, 2));
buildModeButtonGroup.add(viewMode2);
viewMode2.setIcon(getIcon("turn_off"));
viewMode2.setPreferredSize(new java.awt.Dimension(36, 36));
bridgesJPanel.add(viewMode2);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(bridgesJPanel, gridBagConstraints);
tunnelsJPanel.setLayout(new java.awt.FlowLayout(
java.awt.FlowLayout.LEFT, 4, 2));
buildModeButtonGroup.add(viewMode3);
viewMode3.setIcon(getIcon("turn_off"));
viewMode3.setPreferredSize(new java.awt.Dimension(36, 36));
tunnelsJPanel.add(viewMode3);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(tunnelsJPanel, gridBagConstraints);
stationsJPanel.setLayout(new java.awt.FlowLayout(
java.awt.FlowLayout.LEFT, 4, 2));
buildModeButtonGroup.add(viewMode4);
viewMode4.setIcon(getIcon("turn_off"));
viewMode4.setPreferredSize(new java.awt.Dimension(36, 36));
stationsJPanel.add(viewMode4);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(stationsJPanel, gridBagConstraints);
spacer.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 0,
0));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(spacer, gridBagConstraints);
}// GEN-END:initComponents
private void formKeyTyped(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_formKeyTyped
viewMode.doClick();
}// GEN-LAST:event_formKeyTyped
private void formKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_formKeyPressed
viewMode.doClick();
}// GEN-LAST:event_formKeyPressed
private void viewModeActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_viewModeActionPerformed
setVisible(false, false, false, false);
cancelStationPlacement();
setTrackBuilderMode(IGNORE_TRACK);
}// GEN-LAST:event_viewModeActionPerformed
private void bulldozeActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bulldozeActionPerformed
setVisible(false, false, false, false);
cancelStationPlacement();
setTrackBuilderMode(REMOVE_TRACK);
}// GEN-LAST:event_bulldozeActionPerformed
private void addStationActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addStationActionPerformed
setVisible(false, false, false, true);
setTrackBuilderMode(BUILD_STATION);
}// GEN-LAST:event_addStationActionPerformed
private void upgradeTrackActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_upgradeTrackActionPerformed
setVisible(true, true, false, false);
cancelStationPlacement();
setTrackBuilderMode(UPGRADE_TRACK);
}// GEN-LAST:event_upgradeTrackActionPerformed
private void addTrackActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addTrackActionPerformed
setVisible(true, true, true, false);
cancelStationPlacement();
setTrackBuilderMode(BUILD_TRACK);
}// GEN-LAST:event_addTrackActionPerformed
private void setVisible(boolean track, boolean bridges, boolean tunnels,
boolean stations) {
trackJPanel.setVisible(bridges);
bridgesJPanel.setVisible(bridges);
tunnelsJPanel.setVisible(tunnels);
stationsJPanel.setVisible(stations);
}
private void setBuildTrackStrategy() {
ArrayList<Integer> ruleIDs = new ArrayList<Integer>();
ruleIDs.add(selectionSet.get(TrackRule.TrackCategories.track));
ruleIDs.add(selectionSet.get(TrackRule.TrackCategories.bridge));
ruleIDs.add(selectionSet.get(TrackRule.TrackCategories.tunnel));
BuildTrackStrategy bts = BuildTrackStrategy.getMultipleRuleInstance(
ruleIDs, modelRoot.getWorld());
modelRoot.setProperty(ModelRoot.Property.BUILD_TRACK_STRATEGY, bts);
}
private void cancelStationPlacement() {
// Cancel build station mode..
stationBuildModel.getStationCancelAction().actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""));
}
private void setTrackBuilderMode(TrackMoveProducer.BuildMode mode) {
trackMoveProducer.setTrackBuilderMode(mode);
modelRoot.setProperty(ModelRoot.Property.TRACK_BUILDER_MODE, mode);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JToggleButton addStation;
private javax.swing.JToggleButton addTrack;
private javax.swing.ButtonGroup bridgeButtonGroup;
private javax.swing.JPanel bridgesJPanel;
private javax.swing.ButtonGroup buildModeButtonGroup;
private javax.swing.JPanel buildModeJPanel;
private javax.swing.JToggleButton bulldoze;
private javax.swing.JPanel spacer;
private javax.swing.ButtonGroup stationButtonGroup;
private javax.swing.JPanel stationsJPanel;
private javax.swing.ButtonGroup trackButtonGroup;
private javax.swing.JPanel trackJPanel;
private javax.swing.ButtonGroup tunnelButtonGroup;
private javax.swing.JPanel tunnelsJPanel;
private javax.swing.JToggleButton upgradeTrack;
private javax.swing.JToggleButton viewMode;
private javax.swing.JToggleButton viewMode1;
private javax.swing.JToggleButton viewMode2;
private javax.swing.JToggleButton viewMode3;
private javax.swing.JToggleButton viewMode4;
// End of variables declaration//GEN-END:variables
}

StationInfoJPanel

Full name: jfreerails.client.view.StationInfoJPanel

Documentation

/**
* This JPanel displays the supply and demand at a station.
*
* @author Luke
*/

Source Code

/**
* This JPanel displays the supply and demand at a station.
*
* @author Luke
*/
public class StationInfoJPanel extends JPanel implements View,
WorldListListener {
private static final long serialVersionUID = 4050759377680150585L;
private ReadOnlyWorld w;
private ModelRoot modelRoot;
private WorldIterator wi;
/**
* The index of the cargoBundle associated with this station.
*/
private int cargoBundleIndex;
public StationInfoJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jLabel1 = new javax.swing.JLabel();
nextStation = new javax.swing.JButton();
previousStation = new javax.swing.JButton();
close = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
setMinimumSize(new java.awt.Dimension(250, 177));
jLabel1.setFont(new java.awt.Font("Dialog", 0, 10));
jLabel1
.setText("<html>\n<h4 align=\"center\">Supply and Demand at stationName</h4>\n<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"2\">\n <tr>\n <td>&nbsp;</td>\n <td>Will pay<br>for</td>\n <td>Supplies<br>(cars per year)</td>\n <td>Waiting for pickup<br>(car loads)</td>\n </tr>\n <tr>\n <td>Mail</td>\n <td>Yes</td>\n <td>&nbsp;</td>\n <td>&nbsp;</td>\n </tr>\n <tr>\n <td>Passengers</td>\n <td>No</td>\n <td>3</td>\n <td>2.5</td>\n </tr>\n \n</table>\n\n</html>");
jLabel1.setVerticalAlignment(javax.swing.SwingConstants.TOP);
jLabel1.setAlignmentY(0.0F);
jLabel1.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 4, 8);
add(jLabel1, gridBagConstraints);
nextStation.setText("next ->");
nextStation.setMargin(new java.awt.Insets(0, 0, 0, 0));
nextStation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextStationActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(nextStation, gridBagConstraints);
previousStation.setText("<- previous");
previousStation.setMargin(new java.awt.Insets(0, 0, 0, 0));
previousStation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
previousStationActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(previousStation, gridBagConstraints);
close.setText("close");
close.setMargin(new java.awt.Insets(0, 0, 0, 0));
close.setMaximumSize(new java.awt.Dimension(65, 22));
close.setMinimumSize(new java.awt.Dimension(65, 22));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(close, gridBagConstraints);
}// GEN-END:initComponents
private void previousStationActionPerformed(java.awt.event.ActionEvent evt) {
// GEN-FIRST:event_previousStationActionPerformed
// Add your handling code here:
if (wi.previous()) {
ImPoint p = new ImPoint(((StationModel) wi.getElement())
.getStationX(), ((StationModel) wi.getElement())
.getStationY());
this.modelRoot.setProperty(ModelRoot.Property.CURSOR_POSITION, p);
display();
} else {
throw new IllegalStateException();
}
} // GEN-LAST:event_previousStationActionPerformed
private void nextStationActionPerformed(java.awt.event.ActionEvent evt) {
// GEN-FIRST:event_nextStationActionPerformed
// Add your handling code here:
if (wi.next()) {
ImPoint p = new ImPoint(((StationModel) wi.getElement())
.getStationX(), ((StationModel) wi.getElement())
.getStationY());
this.modelRoot.setProperty(ModelRoot.Property.CURSOR_POSITION, p);
display();
} else {
throw new IllegalStateException();
}
} // GEN-LAST:event_nextStationActionPerformed
public void setup(ModelRoot mr, RenderersRoot vl, Action al) {
this.wi = new NonNullElements(KEY.STATIONS, mr.getWorld(), mr
.getPrincipal());
addComponentListener(componentListener);
this.w = mr.getWorld();
this.modelRoot = mr;
this.close.addActionListener(al);
}
public void setStation(int stationNumber) {
this.wi.gotoIndex(stationNumber);
display();
}
private void display() {
if (wi.getRowID() > 0) {
this.previousStation.setEnabled(true);
} else {
this.previousStation.setEnabled(false);
}
if (wi.getRowID() < (wi.size() - 1)) {
this.nextStation.setEnabled(true);
} else {
this.nextStation.setEnabled(false);
}
int stationNumber = wi.getIndex();
String label;
if (stationNumber != WorldIterator.BEFORE_FIRST) {
StationModel station = (StationModel) w.get(modelRoot.getPrincipal(),
KEY.STATIONS, stationNumber);
FreerailsTile tile = (FreerailsTile) w
.getTile(station.x, station.y);
String stationTypeName = tile.getTrackPiece().getTrackRule().getTypeName();
cargoBundleIndex = station.getCargoBundleID();
ImmutableCargoBundle cargoWaiting = (ImmutableCargoBundle) w.get(
modelRoot
.getPrincipal(), KEY.CARGO_BUNDLES, station.getCargoBundleID());
String title = "<h2 align=\"center\">" + station.getStationName()
+ " (" + stationTypeName + ")</h2>";
String table = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"3\"><tr><td>&nbsp;</td>\n <td>Will pay for</td>\n <td>Supplies / cars per year</td><td>Waiting for pickup / car loads</td> </tr>";
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
// get the values
CargoType cargoType = (CargoType) w.get(SKEY.CARGO_TYPES, i);
String demanded = (station.getDemand().isCargoDemanded(i) ? "Yes"
: "No");
int amountSupplied = station.getSupply().getSupply(i);
String supply = (amountSupplied > 0) ? String
.valueOf(amountSupplied
/ WagonType.UNITS_OF_CARGO_PER_WAGON)
: "&nbsp;";
int amountWaiting = cargoWaiting.getAmount(i);
String waiting = (amountWaiting > 0) ? String
.valueOf(amountWaiting
/ WagonType.UNITS_OF_CARGO_PER_WAGON)
: "&nbsp;";
// build the html
table += "<tr>";
table += "<td>" + cargoType.getDisplayName() + "</td>";
table += "<td>" + demanded + "</td>";
table += "<td>" + supply + "</td>";
table += "<td>" + waiting + "</td>";
table += "</tr>";
}
table += "</table>";
label = "<html>" + title + table + "</html>";
} else {
cargoBundleIndex = WorldIterator.BEFORE_FIRST;
label = "<html><h2 align=\"center\">No Station "
+ "Selected</h2></html>";
}
jLabel1.setText(label);
this.repaint();
}
private final ComponentAdapter componentListener = new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent e) {
}
@Override
public void componentShown(ComponentEvent e) {
int i = wi.getIndex();
wi.reset();
if (i != WorldIterator.BEFORE_FIRST) {
wi.gotoIndex(i);
}
display();
}
};
private FreerailsSerializable lastCargoBundle = null;
@Override
protected void paintComponent(Graphics g) {
/* We need to update if the cargo bundle has changed. */
FreerailsPrincipal playerPrincipal = this.modelRoot.getPrincipal();
/*
* Avoid a array out of bounds exception when there are no stations and
* the stations tab is visible.
*/
if (w.boundsContain(playerPrincipal, KEY.CARGO_BUNDLES,
cargoBundleIndex)) {
FreerailsSerializable currentCargoBundle = w.get(playerPrincipal,
KEY.CARGO_BUNDLES, this.cargoBundleIndex);
if (lastCargoBundle != currentCargoBundle) {
this.display();
lastCargoBundle = currentCargoBundle;
}
}
super.paintComponent(g);
}
private void reactToUpdate(KEY key, int changedIndex, boolean isAddition) {
if (!isVisible()) {
return;
}
int currentIndex = wi.getIndex();
if (key == KEY.CARGO_BUNDLES) {
if (changedIndex == cargoBundleIndex) {
/* update our cargo bundle */
display();
return;
}
} else if (key == KEY.STATIONS) {
wi.reset();
if (currentIndex != WorldIterator.BEFORE_FIRST) {
if (currentIndex < wi.size()) {
wi.gotoIndex(currentIndex);
} else {
currentIndex = WorldIterator.BEFORE_FIRST;
}
}
if (isAddition && wi.getIndex() == WorldIterator.BEFORE_FIRST) {
if (wi.next()) {
display();
}
}
if (currentIndex == changedIndex
|| currentIndex == WorldIterator.BEFORE_FIRST) {
display();
}
}
return;
}
public void listUpdated(KEY key, int index, FreerailsPrincipal principal) {
if (modelRoot.getPrincipal().equals(principal))
reactToUpdate(key, index, false);
}
public void itemAdded(KEY key, int index, FreerailsPrincipal principal) {
if (modelRoot.getPrincipal().equals(principal))
reactToUpdate(key, index, true);
}
public void itemRemoved(KEY key, int index, FreerailsPrincipal principal) {
if (modelRoot.getPrincipal().equals(principal))
reactToUpdate(key, index, false);
}
void removeCloseButton() {
this.remove(close);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton close;
private javax.swing.JLabel jLabel1;
private javax.swing.JButton nextStation;
private javax.swing.JButton previousStation;
// End of variables declaration//GEN-END:variables
}

CargoWaitingAndDemandedJPanel

Full name: jfreerails.client.view.CargoWaitingAndDemandedJPanel

Documentation

/**
* A JPanel that displays the cargo waiting and demanded at a station - used on
* the select station popup window.
*
* @author Luke
*/

Source Code

/**
* A JPanel that displays the cargo waiting and demanded at a station - used on
* the select station popup window.
*
* @author Luke
*/
public class CargoWaitingAndDemandedJPanel extends javax.swing.JPanel implements
View {
private static final long serialVersionUID = 3760559784860071476L;
private ReadOnlyWorld world;
private FreerailsPrincipal principal;
public CargoWaitingAndDemandedJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
stationName = new javax.swing.JLabel();
waiting = new javax.swing.JLabel();
waitingJTable = new javax.swing.JTable();
demands = new javax.swing.JLabel();
demandsJList = new javax.swing.JList();
spacer = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(100, 200));
jScrollPane1.setBorder(null);
jScrollPane1
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jPanel1.setLayout(new java.awt.GridBagLayout());
stationName.setText("Station Name");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
jPanel1.add(stationName, gridBagConstraints);
waiting.setText("Waiting");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
jPanel1.add(waiting, gridBagConstraints);
waitingJTable.setBackground(javax.swing.UIManager.getDefaults()
.getColor("Button.background"));
waitingJTable.setFont(new java.awt.Font("Dialog", 0, 10));
waitingJTable.setModel(new javax.swing.table.DefaultTableModel(
new Object[][] { { "Mail", "4" }, { "Passengers", null } },
new String[] { "Title 1", "Title 2" }));
waitingJTable
.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
waitingJTable.setFocusable(false);
waitingJTable.setRequestFocusEnabled(false);
waitingJTable.setRowSelectionAllowed(false);
waitingJTable.setShowHorizontalLines(false);
waitingJTable.setShowVerticalLines(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
jPanel1.add(waitingJTable, gridBagConstraints);
demands.setText("Demands");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel1.add(demands, gridBagConstraints);
demandsJList.setBackground(javax.swing.UIManager.getDefaults()
.getColor("Button.background"));
demandsJList.setFont(new java.awt.Font("Dialog", 0, 10));
demandsJList.setFocusable(false);
demandsJList.setRequestFocusEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
jPanel1.add(demandsJList, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel1.add(spacer, gridBagConstraints);
jScrollPane1.setViewportView(jPanel1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}// GEN-END:initComponents
public void setup(ModelRoot model, RenderersRoot vl,
Action closeAction) {
this.world = model.getWorld();
this.principal = model.getPrincipal();
}
public void display(int newStationID) {
StationModel station = (StationModel) world.get(principal,
KEY.STATIONS, newStationID);
this.stationName.setText(station.getStationName());
final ImmutableCargoBundle cargoWaiting = (ImmutableCargoBundle) world
.get(principal, KEY.CARGO_BUNDLES, station.getCargoBundleID());
// count the number of cargo types waiting and demanded.
final ArrayList<String> typeWaiting = new ArrayList<String>();
final ArrayList<Integer> quantityWaiting = new ArrayList<Integer>();
final Vector<String> typeDemanded = new Vector<String>();
for (int i = 0; i < world.size(SKEY.CARGO_TYPES); i++) {
CargoType cargoType = (CargoType) world.get(SKEY.CARGO_TYPES, i);
int amountWaiting = cargoWaiting.getAmount(i);
if (0 != amountWaiting) {
typeWaiting.add(cargoType.getDisplayName());
int carloads = amountWaiting
/ WagonType.UNITS_OF_CARGO_PER_WAGON;
quantityWaiting.add(new Integer(carloads));
}
if (station.getDemand().isCargoDemanded(i)) {
typeDemanded.add(cargoType.getDisplayName());
}
}
/*
* The table shows the cargo waiting at the station. First column is
* cargo type; second column is quantity in carloads.
*/
TableModel tableModel = new AbstractTableModel() {
private static final long serialVersionUID = 3760559784860071476L;
public int getRowCount() {
return typeWaiting.size();
}
public int getColumnCount() {
return 2;
}
public Object getValueAt(int row, int column) {
if (0 == column) {
return typeWaiting.get(row);
}
return quantityWaiting.get(row);
}
};
this.waitingJTable.setModel(tableModel);
/* The list shows the cargo demanded by the station. */
this.demandsJList.setListData(typeDemanded);
this.invalidate();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel demands;
private javax.swing.JList demandsJList;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JPanel spacer;
private javax.swing.JLabel stationName;
private javax.swing.JLabel waiting;
private javax.swing.JTable waitingJTable;
// End of variables declaration//GEN-END:variables
}

NearestStationFinder

Full name: jfreerails.client.view.NearestStationFinder

Documentation

/**
* Provides methods that find the nearest station in a given direction, used by
* the select station popup window.
*
* @author Luke
*
*/

Source Code

/**
* Provides methods that find the nearest station in a given direction, used by
* the select station popup window.
*
* @author Luke
*
*/
public class NearestStationFinder {
public static final int NOT_FOUND = Integer.MIN_VALUE;
private final ReadOnlyWorld world;
private final FreerailsPrincipal principal;
private final int MAX_DISTANCE_TO_SELECT_SQUARED = 20 * 20;
public NearestStationFinder(ReadOnlyWorld w, FreerailsPrincipal player) {
world = w;
this.principal = player;
}
public int findNearestStation(int x, int y) {
// Find nearest station.
int distanceToClosestSquared = Integer.MAX_VALUE;
NonNullElements it = new NonNullElements(KEY.STATIONS, world, principal);
int nearestStation = NOT_FOUND;
while (it.next()) {
StationModel station = (StationModel) it.getElement();
int deltaX = x - station.x;
int deltaY = y - station.y;
int distanceSquared = deltaX * deltaX + deltaY * deltaY;
if (distanceSquared < distanceToClosestSquared
&& MAX_DISTANCE_TO_SELECT_SQUARED > distanceSquared) {
distanceToClosestSquared = distanceSquared;
nearestStation = it.getIndex();
}
}
return nearestStation;
}
public int findNearestStationInDirection(int startStation, Step direction) {
int distanceToClosestSquared = Integer.MAX_VALUE;
NonNullElements it = new NonNullElements(KEY.STATIONS, world, principal);
StationModel currentStation = (StationModel) world.get(principal,
KEY.STATIONS, startStation);
int nearestStation = NOT_FOUND;
while (it.next()) {
StationModel station = (StationModel) it.getElement();
int deltaX = station.x - currentStation.x;
int deltaY = station.y - currentStation.y;
int distanceSquared = deltaX * deltaX + deltaY * deltaY;
boolean closer = distanceSquared < distanceToClosestSquared;
boolean notTheSameStation = startStation != it.getIndex();
boolean inRightDirection = isInRightDirection(direction, deltaX,
deltaY);
if (closer && inRightDirection && notTheSameStation) {
distanceToClosestSquared = distanceSquared;
nearestStation = it.getIndex();
}
}
return nearestStation;
}
/**
* Returns true if the angle between direction and the vector (deltaX,
* deltaY) is less than 45 degrees.
*/
private boolean isInRightDirection(Step direction, int deltaX, int deltaY) {
boolean isDiagonal = direction.deltaX * direction.deltaY != 0;
boolean sameXDirection = (direction.deltaX * deltaX) > 0;
boolean sameYDirection = (direction.deltaY * deltaY > 0);
boolean deltaXisLongerThanDeltaY = deltaX * deltaX < deltaY * deltaY;
if (isDiagonal) {
return sameXDirection && sameYDirection;
}
if (0 == direction.deltaX) {
return deltaXisLongerThanDeltaY && sameYDirection;
}
return !deltaXisLongerThanDeltaY && sameXDirection;
}
}

FreerailsCursor

Full name: jfreerails.client.view.FreerailsCursor

Documentation

/**
* Paints the cursor on the map, note the cursor's position is stored on the
* ModelRoot under the key CURSOR_POSITION.
*
* @author Luke
*/

Source Code

/**
* Paints the cursor on the map, note the cursor's position is stored on the
* ModelRoot under the key CURSOR_POSITION.
*
* @author Luke
*/
final public class FreerailsCursor {
private final Image buildTrack, upgradeTrack, removeTrack, infoMode;
private final ModelRoot modelRoot;
/** The location of the cursor last time paintCursor(.) was called. */
private ImPoint lastCursorPosition = new ImPoint();
/** The time in ms the cursor arrived at its current position. */
private long timeArrived = 0;
/**
* Creates a new FreerailsCursor.
*
* @throws IOException
*/
public FreerailsCursor(ModelRoot mr, RenderersRoot rr) throws IOException {
this.modelRoot = mr;
modelRoot.setProperty(ModelRoot.Property.CURSOR_MESSAGE, null);
buildTrack = rr.getImage("cursor/buildtrack.png");
upgradeTrack = rr.getImage("cursor/upgradetrack.png");
removeTrack = rr.getImage("cursor/removetrack.png");
infoMode = rr.getImage("cursor/infomode.png");
}
/**
* Paints the cursor. The method calculates position to paint it based on
* the tile size and the cursor's map position.
*
* @param g
* The graphics object to paint the cursor on.
* @param tileSize
* The dimensions of a tile.
*/
public void paintCursor(Graphics g, Dimension tileSize) {
Graphics2D g2 = (Graphics2D) g;
TrackMoveProducer.BuildMode buildMode = (TrackMoveProducer.BuildMode) modelRoot
.getProperty(ModelRoot.Property.TRACK_BUILDER_MODE);
ImPoint cursorMapPosition = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.CURSOR_POSITION);
/* Has the cursor moved since we last painted it? */
if (!cursorMapPosition.equals(lastCursorPosition)) {
lastCursorPosition = cursorMapPosition;
timeArrived = System.currentTimeMillis();
}
int x = cursorMapPosition.x * tileSize.width;
int y = cursorMapPosition.y * tileSize.height;
Image cursor = null;
switch (buildMode) {
case BUILD_TRACK:
cursor = buildTrack;
break;
case REMOVE_TRACK:
cursor = removeTrack;
break;
case UPGRADE_TRACK:
cursor = upgradeTrack;
break;
case IGNORE_TRACK:
cursor = infoMode;
break;
case BUILD_STATION:
cursor = buildTrack;
break;
}
Boolean b = (Boolean) modelRoot
.getProperty(ModelRoot.Property.IGNORE_KEY_EVENTS);
long time = System.currentTimeMillis() - timeArrived;
boolean show = ((time / 500) % 2) == 0;
if (show && !b.booleanValue()) {
g.drawImage(cursor, x, y, null);
}
// Second, draw a message below the cursor if appropriate.
String message = (String) modelRoot
.getProperty(ModelRoot.Property.CURSOR_MESSAGE);
if (null != message && !message.equals("")) {
int fontSize = 12;
Font font = new Font("Arial", 0, fontSize);
FontRenderContext frc = g2.getFontRenderContext();
TextLayout layout = new TextLayout(message, font, frc);
// We want the message to be centered below the cursor.
float visibleAdvance = layout.getVisibleAdvance();
float textX = (x + (tileSize.width / 2) - (visibleAdvance / 2));
float textY = y + tileSize.height + fontSize + 5;
g.setColor(java.awt.Color.white);
layout.draw(g2, textX, textY);
}
// Draw a big white dot at the target point.
ImPoint targetPoint = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.THINKING_POINT);
if (null != targetPoint) {
time = System.currentTimeMillis();
int dotSize;
if ((time % 500) > 250) {
dotSize = BuildTrackRenderer.BIG_DOT_WIDTH;
} else {
dotSize = BuildTrackRenderer.SMALL_DOT_WIDTH;
}
g.setColor(Color.WHITE);
x = targetPoint.x * tileSize.width + (tileSize.width - dotSize) / 2;
y = targetPoint.y * tileSize.width + (tileSize.height - dotSize)
/ 2;
g.fillOval(x, y, dotSize, dotSize);
}
}
}

LeaderBoardJPanel

Full name: jfreerails.client.view.LeaderBoardJPanel

Documentation

/**
* A JPanel that displays the details of the players ordered by net worth.
*
* @author Luke
*/

Source Code

/**
* A JPanel that displays the details of the players ordered by net worth.
*
* @author Luke
*/
public class LeaderBoardJPanel extends JPanel implements View {
private static final long serialVersionUID = 3258131375298066229L;
private JList playersList = null;
private ActionListener submitButtonCallBack = null;
private Vector<PlayerDetails> values;
/**
* This method initializes
*/
public LeaderBoardJPanel() {
super();
values = new Vector<PlayerDetails>();
Random rand = new Random();
for (int i = 0; i < 5; i++) {
PlayerDetails p = new PlayerDetails();
p.networth = new Money(rand.nextInt(100));
values.add(p);
}
initialize();
}
/**
* This method initializes this
*/
private void initialize() {
this.add(getPlayersList(), null);
java.awt.event.MouseAdapter mouseAdapter = new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
if (null == submitButtonCallBack) {
System.err.println("mouseClicked");
} else {
submitButtonCallBack.actionPerformed(new ActionEvent(
this, 0, null));
}
}
};
this.addMouseListener(mouseAdapter);
this.playersList.addMouseListener(mouseAdapter);
this.setSize(getPreferredSize());
}
/**
* This method initializes jList
*
* @return javax.swing.JList
*/
private JList getPlayersList() {
if (playersList == null) {
playersList = new JList();
playersList
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
playersList.setRequestFocusEnabled(false);
playersList.setEnabled(true);
Collections.sort(values);
playersList.setListData(values);
}
return playersList;
}
public void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
ReadOnlyWorld w = modelRoot.getWorld();
values.clear();
this.submitButtonCallBack = closeAction;
for (int player = 0; player < w.getNumberOfPlayers(); player++) {
PlayerDetails details = new PlayerDetails();
FreerailsPrincipal principal = w.getPlayer(player).getPrincipal();
details.name = principal.getName();
NonNullElements stations = new NonNullElements(KEY.STATIONS, w,
principal);
details.stations = stations.size();
TransactionAggregator networth = new NetWorthCalculator(
w, principal);
details.networth = networth.calculateValue();
values.add(details);
}
Collections.sort(values);
playersList.setListData(values);
setSize(getPreferredSize());
}
/**
* Stores the details a player that are shown on the leaderboard.
*
* @author Luke
*/
static class PlayerDetails implements Comparable<PlayerDetails> {
String name = "player";
Money networth = new Money(0);
int stations = 0;
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(name);
sb.append(", ");
sb.append(networth.toString());
sb.append(" net worth, ");
sb.append(stations);
sb.append(" stations.");
return sb.toString();
}
public int compareTo(PlayerDetails test) {
long l = test.networth.getAmount() - networth.getAmount();
return (int) l;
}
}
} // @jve:decl-index=0:visual-constraint="67,32"

SelectEngineJPanel

Full name: jfreerails.client.view.SelectEngineJPanel

Documentation

/**
* This JPanel lets the user select an engine from a list.
*
* @author lindsal8
*
*/

Source Code

/**
* This JPanel lets the user select an engine from a list.
*
* @author lindsal8
*
*/
public class SelectEngineJPanel extends javax.swing.JPanel implements View {
private static final long serialVersionUID = 4122537730158179638L;
public SelectEngineJPanel() {
initComponents();
jList1ValueChanged(null); // Disable the ok button if no engine type
// is selected.
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
okjButton = new javax.swing.JButton();
canceljButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(400, 350));
okjButton.setText("OK");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 9, 10);
add(okjButton, gridBagConstraints);
canceljButton.setText("Cancel");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
add(canceljButton, gridBagConstraints);
jList1
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1
.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(
javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jScrollPane1.setViewportView(jList1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}// GEN-END:initComponents
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) { // GEN-FIRST:event_jList1ValueChanged
// We need to disable the OK button if no engine type is selected.
if (-1 == jList1.getSelectedIndex()) {
okjButton.setEnabled(false);
} else {
okjButton.setEnabled(true);
}
} // GEN-LAST:event_jList1ValueChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton canceljButton;
private javax.swing.JList jList1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton okjButton;
// End of variables declaration//GEN-END:variables
final private class TrainCellRenderer implements ListCellRenderer {
final JLabel label;
final RenderersRoot rr;
public TrainCellRenderer(RenderersRoot vl) {
rr = vl;
label = new JLabel();
}
public Component getListCellRendererComponent(JList list, Object value,
/* value to display */
int index, /* cell index */
boolean isSelected, /* is the cell selected */
boolean cellHasFocus) /* the list and the cell have the focus */{
EngineType engine = (EngineType) value;
label.setFont(new java.awt.Font("Dialog", 0, 12));
String text = "<html><body>" + (isSelected ? "<strong>" : "")
+ engine.getEngineTypeName() + "<br>"
+ engine.getMaxSpeed() + " m.p.h. "
+ engine.getPowerAtDrawbar() + " hp $"
+ engine.getPrice().toString()
+ (isSelected ? "</strong>" : "") + "</body></html>";
label.setText(text);
Image image = rr.getEngineImages(index).getSideOnImage();
int height = image.getHeight(null);
int width = image.getWidth(null);
int scale = height / 50;
ImageIcon icon = new ImageIcon(image.getScaledInstance(width
/ scale, height / scale, Image.SCALE_FAST));
label.setIcon(icon);
return label;
}
}
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
jList1.setModel(new World2ListModelAdapter(mr.getWorld(),
SKEY.ENGINE_TYPES));
jList1.setCellRenderer(new TrainCellRenderer(vl));
okjButton.addActionListener(closeAction);
}
/**
* Removes any existing ActionListener listeners from the cancel button,
* then adds the specified one.
*/
void setCancelButtonActionListener(ActionListener l) {
ActionListener[] oldListeners = canceljButton.getActionListeners();
for (int i = 0; i < oldListeners.length; i++) {
canceljButton.removeActionListener(oldListeners[i]);
}
this.canceljButton.addActionListener(l);
}
/**
* Returns the number of the currently selected engine type.
*
*/
public int getEngineType() {
return jList1.getSelectedIndex();
}
}

BalanceSheetHtmlJPanel

Full name: jfreerails.client.view.BalanceSheetHtmlJPanel

Documentation

/**
* A HtmlJPanel that displays the balance sheet.
*
* @author Luke
*
*/

Source Code

/**
* A HtmlJPanel that displays the balance sheet.
*
* @author Luke
*
*/
public class BalanceSheetHtmlJPanel extends HtmlJPanel implements View {
private static final long serialVersionUID = 3257009873370886964L;
private String template;
private int lastNumTransactions = 0;
private ModelRoot modelRoot;
public BalanceSheetHtmlJPanel() {
super();
URL url = BalanceSheetHtmlJPanel.class
.getResource("/jfreerails/client/view/balance_sheet.htm");
template = loadText(url);
}
@Override
public void setup(ModelRoot modelRoot, RenderersRoot vl, Action closeAction) {
super.setup(modelRoot, vl, closeAction);
this.modelRoot = modelRoot;
updateHtml();
}
private void updateHtml() {
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
BalanceSheetGenerator balanceSheetGenerator = new BalanceSheetGenerator(
world, playerPrincipal);
String populatedTemplate = populateTokens(template,
balanceSheetGenerator);
setHtml(populatedTemplate);
}
@Override
protected void paintComponent(Graphics g) {
/* Check to see if the text needs updating before painting. */
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
int currentNumberOfTransactions = world
.getNumberOfTransactions(playerPrincipal);
if (currentNumberOfTransactions != lastNumTransactions) {
updateHtml();
}
super.paintComponent(g);
}
}

TerrainInfoJPanel

Full name: jfreerails.client.view.TerrainInfoJPanel

Documentation

/**
* This JPanel shows information on a terrain type.
*
* @author Luke
*/

Source Code

/**
* This JPanel shows information on a terrain type.
*
* @author Luke
*/
public class TerrainInfoJPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 3258131375164045363L;
private RenderersRoot rr;
private ReadOnlyWorld w;
public TerrainInfoJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
terrainImage = new javax.swing.JLabel();
terrainName = new javax.swing.JLabel();
terrainDescription = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
terrainImage.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/jfreerails/client/graphics/terrain/City_0.png")));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(8, 8, 4, 4);
add(terrainImage, gridBagConstraints);
terrainName.setFont(new java.awt.Font("Dialog", 1, 14));
terrainName.setText("City");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 8);
add(terrainName, gridBagConstraints);
terrainDescription.setFont(new java.awt.Font("Dialog", 0, 12));
terrainDescription
.setText("<html>\n<p>Right-of-Way costs X per mile. </p>\n<table width=\"75%\" >\n <tr> \n <td><strong>Supplies:</strong></td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td>Mail </td>\n <td>2</td>\n </tr>\n <tr> \n <td>Passengers</td>\n <td>2</td>\n </tr>\n <tr> \n <td> <strong>Demands</strong></td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td>Mail</td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td>Passengers</td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td><strong>Converts</strong></td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td>Livestock to Food</td>\n <td>&nbsp;</td>\n </tr>\n <tr>\n <td>Steel to Goods</td>\n <td>&nbsp;</td>\n </tr>\n</table>\n</html>");
terrainDescription.setVerticalAlignment(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 8, 4, 8);
add(terrainDescription, gridBagConstraints);
}// GEN-END:initComponents
public void setup(ReadOnlyWorld w, RenderersRoot vl) {
this.w = w;
this.rr = vl;
}
public void setTerrainType(int typeNumber) {
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES, typeNumber);
String row = "<p>Right-of-Way costs $" + type.getRightOfWay()
+ " per mile. </p>";
String tableString = "";
int cargosProduced = type.getProduction().size();
int cargosConsumed = type.getConsumption().size();
int cargosConverted = type.getConversion().size();
if ((cargosProduced + cargosConsumed + cargosConverted) > 0) {
// if the terrain type produces, consumes, or converts anything.
tableString = "<table width=\"75%\" >";
if (cargosProduced != 0) {
tableString += "<tr> <td><strong>Supplies</strong></td> <td>&nbsp;</td> </tr>";
for (int i = 0; i < cargosProduced; i++) {
Production p = type.getProduction().get(i);
CargoType c = (CargoType) w.get(SKEY.CARGO_TYPES, p
.getCargoType());
String supply = String.valueOf(p.getRate()
/ WagonType.UNITS_OF_CARGO_PER_WAGON);
tableString += "<tr> <td>" + c.getDisplayName()
+ " </td><td>" + supply + "</td></tr>";
}
}
if (cargosConsumed != 0) {
tableString += "<tr> <td><strong>Demands</strong></td> <td>&nbsp;</td> </tr>";
for (int i = 0; i < cargosConsumed; i++) {
Consumption p = type.getConsumption().get(i);
CargoType c = (CargoType) w.get(SKEY.CARGO_TYPES, p
.getCargoType());
tableString += "<tr> <td>" + c.getDisplayName()
+ " </td><td>&nbsp;</td></tr>";
}
}
if (cargosConverted != 0) {
tableString += "<tr> <td><strong>Converts</strong></td> <td>&nbsp;</td> </tr>";
for (int i = 0; i < cargosConverted; i++) {
Conversion p = type.getConversion().get(i);
CargoType input = (CargoType) w.get(SKEY.CARGO_TYPES, p
.getInput());
CargoType output = (CargoType) w.get(SKEY.CARGO_TYPES, p
.getOutput());
tableString += "<tr> <td colspan=\"2\">"
+ input.getDisplayName() + " to "
+ output.getDisplayName() + "</td></tr>";
}
}
tableString += "</table> ";
}
String labelString = "<html>" + row + tableString + "</html>";
terrainDescription.setText(labelString);
terrainName.setText(type.getDisplayName());
Image tileIcon = rr.getTileViewWithNumber(typeNumber)
.getDefaultIcon();
terrainImage.setIcon(new ImageIcon(tileIcon));
repaint();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel terrainDescription;
private javax.swing.JLabel terrainImage;
private javax.swing.JLabel terrainName;
// End of variables declaration//GEN-END:variables
}

SelectStationJPanel

Full name: jfreerails.client.view.SelectStationJPanel

Documentation

/**
* This JPanel lets the user select a station from a map and add it to a train
* schedule.
*
* @author Luke
*/

Source Code

/**
* This JPanel lets the user select a station from a map and add it to a train
* schedule.
*
* @author Luke
*/
public class SelectStationJPanel extends javax.swing.JPanel implements View {
private static final long serialVersionUID = 3258411750662877488L;
private ReadOnlyWorld world;
private ActionListener submitButtonCallBack;
private int selectedStationID = 0;
private int selectedOrderNumber = 1;
private MutableSchedule schedule;
private Rectangle mapRect = new Rectangle();
private Rectangle visibleMapTiles = new Rectangle();
private double scale = 1;
private boolean needsUpdating = true;
private FreerailsPrincipal principal;
public SelectStationJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
cargoWaitingAndDemandedJPanel1 = new jfreerails.client.view.CargoWaitingAndDemandedJPanel();
jLabel1 = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(500, 350));
addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
@Override
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
formMouseClicked(evt);
}
});
addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
@Override
public void mouseMoved(java.awt.event.MouseEvent evt) {
formMouseMoved(evt);
}
});
cargoWaitingAndDemandedJPanel1
.setBorder(new javax.swing.border.LineBorder(
new java.awt.Color(0, 0, 0)));
cargoWaitingAndDemandedJPanel1.setPreferredSize(new java.awt.Dimension(
165, 300));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(cargoWaitingAndDemandedJPanel1, gridBagConstraints);
jLabel1.setText("Train #1 Stop 1");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weightx = 1.0;
add(jLabel1, gridBagConstraints);
}// GEN-END:initComponents
private void formComponentShown(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_formComponentShown
setZoom();
}// GEN-LAST:event_formComponentShown
private void formMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_formMouseClicked
formMouseMoved(evt);
needsUpdating = true;
this.submitButtonCallBack.actionPerformed(null);
}// GEN-LAST:event_formMouseClicked
private void formKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_formKeyPressed
try {
Step v = KeyCode2OneTileMoveVector.getInstanceMappedToKey(evt
.getKeyCode());
// now find nearest station in direction of the vector.
NearestStationFinder stationFinder = new NearestStationFinder(
this.world, this.principal);
int station = stationFinder.findNearestStationInDirection(
this.selectedStationID, v);
if (selectedStationID != station
&& station != NearestStationFinder.NOT_FOUND) {
selectedStationID = station;
cargoWaitingAndDemandedJPanel1.display(selectedStationID);
this.validate();
this.repaint();
}
} catch (NoSuchElementException e) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
needsUpdating = true;
submitButtonCallBack.actionPerformed(null);
}
// The key pressed isn't mapped to a OneTileMoveVector so do
// nothing.
}
}// GEN-LAST:event_formKeyPressed
private void formComponentResized(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_formComponentResized
setZoom();
}// GEN-LAST:event_formComponentResized
private void formMouseMoved(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_formMouseMoved
// Add your handling code here:
double x = evt.getX();
x = x / scale + visibleMapTiles.x;
double y = evt.getY();
y = y / scale + visibleMapTiles.y;
NearestStationFinder stationFinder = new NearestStationFinder(
this.world, this.principal);
int station = stationFinder.findNearestStation((int) x, (int) y);
if (selectedStationID != station
&& station != NearestStationFinder.NOT_FOUND) {
selectedStationID = station;
cargoWaitingAndDemandedJPanel1.display(selectedStationID);
this.validate();
this.repaint();
}
}// GEN-LAST:event_formMouseMoved
public void display(MutableSchedule newSchedule, int orderNumber) {
this.schedule = newSchedule;
this.selectedOrderNumber = orderNumber;
TrainOrdersModel order = newSchedule.getOrder(selectedOrderNumber);
this.selectedStationID = order.getStationID();
// Set the text on the title JLabel.
this.jLabel1.setText("Stop " + String.valueOf(selectedOrderNumber + 1));
// Set the station info panel to show the current selected station.
cargoWaitingAndDemandedJPanel1.display(selectedStationID);
}
/**
* Sets the zoom based on the size of the component and the positions of the
* stations.
*/
private void setZoom() {
mapRect = this.getBounds();
Rectangle r = cargoWaitingAndDemandedJPanel1.getBounds();
mapRect.width -= r.width;
int topLeftX = Integer.MAX_VALUE;
int topLeftY = Integer.MAX_VALUE;
int bottomRightX = Integer.MIN_VALUE;
int bottomRightY = Integer.MIN_VALUE;
NonNullElements it = new NonNullElements(KEY.STATIONS, world,
this.principal);
while (it.next()) {
StationModel station = (StationModel) it.getElement();
if (station.x < topLeftX)
topLeftX = station.x;
if (station.y < topLeftY)
topLeftY = station.y;
if (station.x > bottomRightX)
bottomRightX = station.x;
if (station.y > bottomRightY)
bottomRightY = station.y;
}
// Add some padding.
topLeftX -= 10;
topLeftY -= 10;
bottomRightX += 10;
bottomRightY += 10;
int width = bottomRightX - topLeftX;
int height = bottomRightY - topLeftY;
visibleMapTiles = new Rectangle(topLeftX, topLeftY, width, height);
boolean heightConstraintBinds = (visibleMapTiles.getHeight() / visibleMapTiles
.getWidth()) > (mapRect.getHeight() / mapRect.getWidth());
if (heightConstraintBinds) {
scale = mapRect.getHeight() / visibleMapTiles.getHeight();
} else {
scale = mapRect.getWidth() / visibleMapTiles.getWidth();
}
needsUpdating = false;
}
@Override
protected void paintComponent(Graphics g) {
if (needsUpdating) {
this.setZoom();
}
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
NonNullElements it = new NonNullElements(KEY.STATIONS, world,
this.principal);
// Draw track
g2.setColor(Color.BLACK);
for (int x = Math.max(0, visibleMapTiles.x); x < Math.min(
visibleMapTiles.width + visibleMapTiles.x, world.getMapWidth()); x++) {
for (int y = Math.max(0, visibleMapTiles.y); y < Math.min(
visibleMapTiles.height + visibleMapTiles.y, world
.getMapHeight()); y++) {
FreerailsTile tt = (FreerailsTile) world.getTile(x, y);
if (!tt.getTrackPiece().equals(NullTrackPiece.getInstance())) {
double xDouble = x - visibleMapTiles.x;
xDouble = xDouble * scale;
double yDouble = y - visibleMapTiles.y;
yDouble = yDouble * scale;
g.drawRect((int) xDouble, (int) yDouble, 1, 1);
}
}
}
// Draw stations
while (it.next()) {
/*
* (1) The selected station is drawn green. (2) Non-selected
* stations which are on the schedule are drawn blue. (3) Other
* stations are drawn white. (4) If, for instance, station X is the
* first stop on the schedule, "1" is drawn above the station. (5)
* If, for instance, station X is the first and third stop on the
* schedule, "1, 3" is drawn above the station. (6) The stop numbers
* drawn above the stations are drawn using the same colour as used
* to draw the station.
*/
StationModel station = (StationModel) it.getElement();
double x = station.x - visibleMapTiles.x;
x = x * scale;
double y = station.y - visibleMapTiles.y;
y = y * scale;
int xInt = (int) x;
int yInt = (int) y;
String stopNumbersString = "";
boolean stationIsOnSchedule = false;
for (int orderNumber = 0; orderNumber < schedule.getNumOrders(); orderNumber++) {
int stationID = orderNumber == this.selectedOrderNumber ? this.selectedStationID
: schedule.getOrder(orderNumber).getStationID();
if (it.getIndex() == stationID) {
if (stationIsOnSchedule) {
stopNumbersString = stopNumbersString + ", "
+ String.valueOf(orderNumber + 1);
} else {
stopNumbersString = String.valueOf(orderNumber + 1);
}
stationIsOnSchedule = true;
}
}
if (stationIsOnSchedule) {
if (it.getIndex() == selectedStationID) {
g2.setColor(Color.GREEN);
} else {
g2.setColor(Color.BLUE);
}
g2.drawString(stopNumbersString, xInt, yInt - 4);
} else {
g2.setColor(Color.WHITE);
}
g2.fillRect(xInt, yInt, 10, 10);
}
}
public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
cargoWaitingAndDemandedJPanel1.setup(mr, vl, null);
this.world = mr.getWorld();
this.submitButtonCallBack = closeAction;
principal = mr.getPrincipal();
}
public MutableSchedule generateNewSchedule() {
TrainOrdersModel oldOrders, newOrders;
oldOrders = schedule.getOrder(selectedOrderNumber);
newOrders = new TrainOrdersModel(selectedStationID, oldOrders
.getConsist(), oldOrders.getWaitUntilFull(), oldOrders
.isAutoConsist());
schedule.setOrder(selectedOrderNumber, newOrders);
return schedule;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private jfreerails.client.view.CargoWaitingAndDemandedJPanel cargoWaitingAndDemandedJPanel1;
private javax.swing.JLabel jLabel1;
// End of variables declaration//GEN-END:variables
}

MapViewJComponentConcrete

Full name: jfreerails.client.view.MapViewJComponentConcrete

Documentation

/**
* Displays the map, the cursor, and user messages (which are stored on the
* ModelRoot under the keys QUICK_MESSAGE and PERMANENT_MESSAGE).
*
* @author Luke Lindsay
*
*/

Source Code

/**
* Displays the map, the cursor, and user messages (which are stored on the
* ModelRoot under the keys QUICK_MESSAGE and PERMANENT_MESSAGE).
*
* @author Luke Lindsay
*
*/
final public class MapViewJComponentConcrete extends MapViewJComponent
implements ModelRootListener {
private static final long serialVersionUID = 3834868087706236208L;
private static final Font USER_MESSAGE_FONT = new Font("Arial", 0, 12);
private static final Font LARGE_MESSAGE_FONT = new Font("Arial", 0, 24);
/**
* The length of the array is the number of lines. This is necessary since
* Graphics.drawString(..) doesn't know about newline characters
*/
private String[] userMessage = new String[0];
/**
* Message that will appear in the middle of the screen in
* <code>LARGE_MESSAGE_FONT</code>.
*/
private String message = null;
/** Time at which to stop displaying the current user message. */
private long displayMessageUntil = 0;
private FreerailsCursor mapCursor;
/**
* Affects scroll direction and scroll speed relative to the cursor.
* Examples:
* <p>
* 1 := grab map, move 1:1
* <p>
* -2 := invert mouse, scroll twice as fast
*/
private final int LINEAR_ACCEL = -1;
/**
* Affects the granularity of the map scrolling (the map is scrolled in
* tileSize/GRANULARITY intervals). Multiply this value with LINEAR_ACCEL to
* be independent of acceleration.
*/
private final int GRANULARITY = 2 * LINEAR_ACCEL;
/**
* A {@link Robot} to compensate mouse cursor movement.
*/
private static Robot robot;
static {
try {
robot = new Robot();
} catch (java.awt.AWTException e) {
}
}
/**
* Implements a MouseListener for FreerailsCursor-movement (left mouse
* button) and a MouseMotionListener for map-scrolling (right mouse button).
* <p>
* Possible enhancements: setCursor(blankCursor),
* g.draw(cursorimage,lastMouseLocation.x,lastMouseLocation.y,null)
*/
final private class MapViewJComponentMouseAdapter extends MouseInputAdapter {
/**
* Screen location of the mouse cursor, when the second mouse button was
* pressed.
*/
private Point screenLocation = new Point();
private Point lastMouseLocation = new Point();
/**
* A variable to sum up relative mouse movement.
*/
private Point sigmadelta = new Point();
/**
* Where to scroll - Reflects granularity, scroll direction and
* acceleration, respects bounds.
*/
private Point tiledelta = new Point();
@Override
public void mousePressed(MouseEvent evt) {
/*
* Note, moving the cursor using the mouse is now handled in
* UserInputOnMapController
*/
if (SwingUtilities.isRightMouseButton(evt)) {
MapViewJComponentConcrete.this
.setCursor(Cursor
.getPredefinedCursor((LINEAR_ACCEL > 0) ? Cursor.HAND_CURSOR
: Cursor.MOVE_CURSOR));
lastMouseLocation.x = evt.getX();
lastMouseLocation.y = evt.getY();
screenLocation.x = evt.getX();
screenLocation.y = evt.getY();
sigmadelta.x = 0;
sigmadelta.y = 0;
javax.swing.SwingUtilities.convertPointToScreen(screenLocation,
MapViewJComponentConcrete.this);
}
}
@Override
public void mouseReleased(MouseEvent evt) {
MapViewJComponentConcrete.this.setCursor(Cursor
.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
@Override
public void mouseDragged(MouseEvent evt) {
if (SwingUtilities.isRightMouseButton(evt)) {
sigmadelta.x += evt.getX() - lastMouseLocation.x;
sigmadelta.y += evt.getY() - lastMouseLocation.y;
int tileSize = (int) getScale();
tiledelta.x = (sigmadelta.x * GRANULARITY) / tileSize;
tiledelta.y = (sigmadelta.y * GRANULARITY) / tileSize;
tiledelta.x = ((tiledelta.x * tileSize) / GRANULARITY)
* LINEAR_ACCEL;
tiledelta.y = ((tiledelta.y * tileSize) / GRANULARITY)
* LINEAR_ACCEL;
Rectangle vr = MapViewJComponentConcrete.this.getVisibleRect();
Rectangle bounds = MapViewJComponentConcrete.this.getBounds();
int temp; // respect bounds
if ((temp = vr.x - tiledelta.x) < 0) {
sigmadelta.x += temp / LINEAR_ACCEL;
tiledelta.x += temp;
} else if ((temp = (bounds.width) - (vr.x + vr.width)
+ tiledelta.x) < 0) {
sigmadelta.x -= temp / LINEAR_ACCEL;
tiledelta.x -= temp;
}
if ((temp = vr.y - tiledelta.y) < 0) {
sigmadelta.y += temp / LINEAR_ACCEL;
tiledelta.y += temp;
} else if ((temp = (bounds.height) - (vr.y + vr.height)
+ tiledelta.y) < 0) {
sigmadelta.y -= temp / LINEAR_ACCEL;
tiledelta.y -= temp;
}
if (tiledelta.x != 0 || tiledelta.y != 0) {
vr.x -= tiledelta.x;
vr.y -= tiledelta.y;
MapViewJComponentConcrete.this.scrollRectToVisible(vr);
sigmadelta.x -= tiledelta.x / LINEAR_ACCEL;
sigmadelta.y -= tiledelta.y / LINEAR_ACCEL;
lastMouseLocation.x -= tiledelta.x;
lastMouseLocation.y -= tiledelta.y;
}
MapViewJComponentConcrete.robot.mouseMove(screenLocation.x,
screenLocation.y);
}
}
}
@Override
protected void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);
if (null != mapCursor && this.isFocusOwner()) {
mapCursor.paintCursor(g, new java.awt.Dimension(30, 30));
}
if (System.currentTimeMillis() < this.displayMessageUntil) {
Rectangle visRect = this.getVisibleRect();
g.setColor(Color.WHITE);
g.setFont(USER_MESSAGE_FONT);
for (int i = 0; i < userMessage.length; i++) {
g.drawString(this.userMessage[i], 50 + visRect.x, 50
+ visRect.y + i * 20);
}
}
if (message != null) {
Rectangle visRect = this.getVisibleRect();
g.setColor(Color.lightGray);
g.setFont(LARGE_MESSAGE_FONT);
int msgWidth = g.getFontMetrics(LARGE_MESSAGE_FONT).stringWidth(
message);
int msgHeight = g.getFontMetrics(LARGE_MESSAGE_FONT).getHeight();
g.drawString(message,
(int) (visRect.x + (visRect.getWidth() - msgWidth) / 2),
(int) (visRect.y + (visRect.getHeight() - msgHeight) / 2));
}
}
public MapViewJComponentConcrete() {
super();
MapViewJComponentMouseAdapter mva = new MapViewJComponentMouseAdapter();
this.addMouseListener(mva);
this.addMouseMotionListener(mva);
}
public void setup(MapRenderer mv, ModelRootImpl mr, RenderersRoot rr)
throws IOException {
super.setMapView(mv);
this.setBorder(null);
this.mapCursor = new FreerailsCursor(mr, rr);
mr.addPropertyChangeListener(this);
}
public void setup(MapRenderer mv) {
super.setMapView(mv);
}
private void react2cursorMove(ImPoint newPoint, ImPoint oldPoint) {
float scale = getMapView().getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
Rectangle vr = this.getVisibleRect();
Rectangle rectangleSurroundingCursor = new Rectangle(0, 0, 1, 1);
rectangleSurroundingCursor.setLocation((newPoint.x - 1)
* tileSize.width, (newPoint.y - 1) * tileSize.height);
rectangleSurroundingCursor.setSize(tileSize.width * 3,
tileSize.height * 3);
if (!(vr.contains(rectangleSurroundingCursor))) {
int x = newPoint.x * tileSize.width - vr.width / 2;
int y = newPoint.y * tileSize.height - vr.height / 2;
this.scrollRectToVisible(new Rectangle(x, y, vr.width, vr.height));
}
this.repaint((newPoint.x - 1) * tileSize.width, (newPoint.y - 1)
* tileSize.height, tileSize.width * 3, tileSize.height * 3);
this.repaint((oldPoint.x - 1) * tileSize.width, (oldPoint.y - 1)
* tileSize.height, tileSize.width * 3, tileSize.height * 3);
}
public void paintTile(Graphics g, int tileX, int tileY) {
throw new UnsupportedOperationException();
}
public void refreshTile(int x, int y) {
throw new UnsupportedOperationException();
}
public void refreshAll() {
this.getMapView().refreshAll();
}
public void paintRect(Graphics g, Rectangle visibleRect) {
throw new UnsupportedOperationException();
}
public FreerailsCursor getMapCursor() {
return mapCursor;
}
private void println(String s) {
StringTokenizer st = new StringTokenizer(s, "\n");
this.userMessage = new String[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
userMessage[i] = st.nextToken();
i++;
}
// Display the message for 5 seconds.
displayMessageUntil = System.currentTimeMillis() + 1000 * 5;
}
/**
* Checks what triggered the specified PropertyChangeEvent and reacts as
* follows.
* <p>
* (1) If it was ModelRoot.CURSOR_POSITION, scrolls the map if necessary.
* </p>
* <p>
* (2) If it was ModelRoot.QUICK_MESSAGE, display or hide the message as
* appropriate.
* </p>
* <p>
* (3) If it was ModelRoot.PERMANENT_MESSAGE, display or hide the message as
* appropriate.
* </p>
*/
public void propertyChange(ModelRoot.Property p, Object before, Object after) {
if (p.equals(ModelRoot.Property.CURSOR_POSITION)) {
ImPoint newPoint = (ImPoint) after;
ImPoint oldPoint = (ImPoint) before;
if (null == oldPoint) {
oldPoint = new ImPoint();
}
react2cursorMove(newPoint, oldPoint);
} else if (p.equals(ModelRoot.Property.QUICK_MESSAGE)) {
String newMessage = (String) after;
if (null != newMessage) {
println(newMessage);
} else {
// Its null, so stop displaying whatever we where displaying.
displayMessageUntil = Long.MIN_VALUE;
}
} else if (p.equals(ModelRoot.Property.PERMANENT_MESSAGE)) {
message = (String) after;
}
}
}

PlayerColors

Full name: jfreerails.client.view.PlayerColors

Documentation

/**
* Stores a list of colours to use to represent different players.
*
* @author Luke
*
*/

Source Code

/**
* Stores a list of colours to use to represent different players.
*
* @author Luke
*
*/
public class PlayerColors {
private static final Color[] colors = new Color[] { Color.BLUE,
Color.GREEN, Color.CYAN, Color.MAGENTA, Color.ORANGE, Color.YELLOW };// Save
// red
// for
// when
// we
// need
// to
// grab
// the
// player's
// attention!
public static Color getColor(int playerNumber) {
return colors[playerNumber % colors.length];
}
}

Methods

MapViewJComponent

Full name: jfreerails.client.view.MapViewJComponent

Documentation

/**
* JPanel that displays the map and provides methods to handle scrolling.
*
* @author Luke Lindsay 01 November 2001
*/

Source Code

/**
* JPanel that displays the map and provides methods to handle scrolling.
*
* @author Luke Lindsay 01 November 2001
*/
public abstract class MapViewJComponent extends JPanel implements Scrollable,
MapRenderer {
private MapRenderer mapView = new BlankMapRenderer(10);
public MapViewJComponent() {
this.setAutoscrolls(true);
}
public float getScale() {
return getMapView().getScale();
}
@Override
protected void paintComponent(java.awt.Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
java.awt.Rectangle r = this.getVisibleRect();
getMapView().paintRect(g2, r);
}
public int getScrollableUnitIncrement(java.awt.Rectangle rectangle,
int orientation, int direction) {
return (int) getMapView().getScale();
}
public boolean getScrollableTracksViewportWidth() {
return false;
}
public int getScrollableBlockIncrement(java.awt.Rectangle rectangle,
int orientation, int direction) {
if (javax.swing.SwingConstants.VERTICAL == orientation) {
int best = (int) (((rectangle.height / getMapView().getScale()) - 2) * getMapView()
.getScale());
if (best > 0) {
return best;
}
return rectangle.height;
}
float f = ((rectangle.width / getMapView().getScale()) - 2)
* getMapView().getScale();
int best = (int) (f);
if (best > 0) {
return best;
}
return rectangle.width;
}
/**
* Gets the scrollableTracksViewportHeight attribute of the
* MapViewJComponent object.
*
* @return The scrollableTracksViewportHeight value
*/
public boolean getScrollableTracksViewportHeight() {
return false;
}
/**
* Gets the preferredScrollableViewportSize attribute of the
* MapViewJComponent object.
*
* @return The preferredScrollableViewportSize value
*/
public java.awt.Dimension getPreferredScrollableViewportSize() {
return this.getPreferredSize();
}
public void centerOnTile(Point tile) {
float scale = getMapView().getScale();
Rectangle visRect = new Rectangle(this.getVisibleRect());
visRect.x = (int) (tile.x * scale - (visRect.width / 2));
visRect.y = (int) (tile.y * scale - (visRect.height / 2));
this.scrollRectToVisible(visRect);
}
public Dimension getMapSizeInPixels() {
return getMapView().getMapSizeInPixels();
}
@Override
public Dimension getPreferredSize() {
return getMapSizeInPixels();
}
void setMapView(MapRenderer mapView) {
this.mapView = mapView;
}
public MapRenderer getMapView() {
return mapView;
}
}

ActionRoot

Full name: jfreerails.client.view.ActionRoot

Documentation

/**
* Provides access to Actions change the game state and the GUI.
*
* @author Luke
*
*/

Source Code

/**
* Provides access to Actions change the game state and the GUI.
*
* @author Luke
*
*/
public class ActionRoot {
private class BuildTrainDialogAction extends AbstractAction {
private static final long serialVersionUID = 3257853173002416948L;
public BuildTrainDialogAction() {
super("Build Train");
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0));
putValue(SHORT_DESCRIPTION, "Build a new train");
}
public void actionPerformed(ActionEvent e) {
if (dialogueBoxController != null) {
dialogueBoxController.showSelectEngine();
}
}
}
private final BuildTrainDialogAction buildTrainDialogAction = new BuildTrainDialogAction();
private DialogueBoxController dialogueBoxController = null;
private final ServerControlModel serverControls;
private StationBuildModel stationBuildModel;
private TrackMoveProducer trackMoveProducer;
public ActionRoot(ModelRootImpl mr) {
this.serverControls = new ServerControlModel(mr);
}
public Action getBuildTrainDialogAction() {
return buildTrainDialogAction;
}
public DialogueBoxController getDialogueBoxController() {
return dialogueBoxController;
}
public ServerControlModel getServerControls() {
return serverControls;
}
public StationBuildModel getStationBuildModel() {
return stationBuildModel;
}
public TrackMoveProducer getTrackMoveProducer() {
return trackMoveProducer;
}
public void setDialogueBoxController(
DialogueBoxController dialogueBoxController) {
this.dialogueBoxController = dialogueBoxController;
}
/**
* Call this method when a new game is started or a game is loaded.
*/
public void setup(ModelRootImpl modelRoot, RenderersRoot vl) {
serverControls.setup(modelRoot, dialogueBoxController);
if (!modelRoot.hasBeenSetup)
throw new IllegalStateException();
ReadOnlyWorld world = modelRoot.getWorld();
if (world.size(SKEY.TRACK_RULES) > 0) {
trackMoveProducer = new TrackMoveProducer(modelRoot);
stationBuildModel = new StationBuildModel(new StationBuilder(
modelRoot), vl, modelRoot);
}
}
}

BrokerScreenHtmlJFrame

Full name: jfreerails.client.view.BrokerScreenHtmlJFrame

Documentation

/**
*
* @author smackay
* @author Luke
*/

Source Code

/**
*
* @author smackay
* @author Luke
*/
public class BrokerScreenHtmlJFrame extends BrokerJFrame implements View {
private static final long serialVersionUID = 3257003246252800050L;
private String template;
private int lastNumTransactions = 0;
private ModelRoot modelRoot;
public static BrokerScreenGenerator brokerScreenGenerator;
private FinancialDataGatherer financialDataGatherer;
private Action[] buyStock, sellStock;
/** Creates a new instance of BrokerScreenHtmlJPanel */
public BrokerScreenHtmlJFrame() {
super();
URL url = BrokerScreenHtmlJFrame.class
.getResource("/jfreerails/client/view/Broker_Screen.html");
template = loadText(url);
this.setSize(550, 300);
}
private final Action issueBondAction = new AbstractAction("Issue bond") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
if (financialDataGatherer.canIssueBond()) {
Move bondTransaction = new AddTransactionMove(modelRoot
.getPrincipal(),
BondTransaction.issueBond(financialDataGatherer
.nextBondInterestRate()));
modelRoot.doMove(bondTransaction);
}
}
};
private final Action repayBondAction = new AbstractAction("Repay bond") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
Move bondTransaction = new AddTransactionMove(modelRoot
.getPrincipal(), BondTransaction.repayBond(5));
modelRoot.doMove(bondTransaction);
}
};
@Override
public void setup(final ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
super.setup(modelRoot, vl, closeAction);
financialDataGatherer = new FinancialDataGatherer(modelRoot.getWorld(),
modelRoot.getPrincipal());
this.modelRoot = modelRoot;
setupStockMenu();
updateHtml();
// Sets up the BrokerScreen and Adds ActionListeners to the Menu
issueBond.setAction(issueBondAction);
repayBond.setAction(repayBondAction);
}
private void setupStockMenu(){
stocks.removeAll();
ReadOnlyWorld world = modelRoot.getWorld();
int thisPlayerId = world.getID(modelRoot.getPrincipal());
int numberOfPlayers = world.getNumberOfPlayers();
buyStock = new Action[numberOfPlayers];
sellStock = new Action[numberOfPlayers];
for(int playerId = 0 ; playerId < numberOfPlayers; playerId++){
final boolean isThisPlayer = playerId == thisPlayerId;
final int otherPlayerId = playerId;
Player otherPlayer = world.getPlayer(playerId);
String playerLabel = isThisPlayer ? "Treasury stock" : otherPlayer.getName();
String buyLabel = "Buy 10,000 shares of " + playerLabel;
String sellLabel = "Sell 10,000 shares of " + playerLabel;
buyStock[playerId] = new AbstractAction(buyLabel) {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
StockPrice stockPrice = new StockPriceCalculator(modelRoot.getWorld()).calculate()[otherPlayerId];
Money sharePrice = isThisPlayer ? stockPrice.treasuryBuyPrice : stockPrice.buyPrice;
StockTransaction t = StockTransaction
.buyOrSellStock(otherPlayerId, StockTransaction.STOCK_BUNDLE_SIZE, sharePrice);
Move move = new AddTransactionMove(modelRoot.getPrincipal(), t);
modelRoot.doMove(move);
updateHtml();
}
};
sellStock[playerId] = new AbstractAction(sellLabel) {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
StockPrice stockPrice = new StockPriceCalculator(modelRoot.getWorld()).calculate()[otherPlayerId];
Money sharePrice = isThisPlayer ? stockPrice.treasurySellPrice : stockPrice.sellPrice;
StockTransaction t = StockTransaction
.buyOrSellStock(otherPlayerId, -StockTransaction.STOCK_BUNDLE_SIZE, sharePrice);
Move move = new AddTransactionMove(modelRoot.getPrincipal(), t);
modelRoot.doMove(move);
updateHtml();
}
};
stocks.add(buyStock[playerId]);
stocks.add(sellStock[playerId]);
}
enableAndDisableActions();
}
private void enableAndDisableActions(){
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal p = modelRoot.getPrincipal();
FinancialDataGatherer thisDataGatherer = new FinancialDataGatherer(
world, p);
StockPrice[] stockPrices = new StockPriceCalculator(world).calculate();
long highestAffordablePrice = world.getCurrentBalance(p).getAmount() / StockTransaction.STOCK_BUNDLE_SIZE;
//Enable and disable stock actions.
for(int playerId = 0; playerId < world.getNumberOfPlayers(); playerId++){
Player temp = modelRoot.getWorld().getPlayer(playerId);
FreerailsPrincipal otherPrincipal = temp.getPrincipal();
FinancialDataGatherer otherDataGatherer = new FinancialDataGatherer(world, otherPrincipal);
//If this RR has stock in other RR, then enable sell stock
boolean hasStockInRR = thisDataGatherer.getStockInRRs()[playerId] > 0;
sellStock[playerId].setEnabled(hasStockInRR);
//If the public own some stock, then enable buy stock.
boolean isStockAvailable = otherDataGatherer.sharesHeldByPublic() > 0;
buyStock[playerId].setEnabled(isStockAvailable);
//Don't let player buy 100% of treasury stock.
if(otherPrincipal.equals(p)){
int treasuryStock = otherDataGatherer.treasuryStock();
int totalStock = otherDataGatherer.totalShares();
if(StockTransaction.STOCK_BUNDLE_SIZE + treasuryStock >= totalStock){
buyStock[playerId].setEnabled(false);
}
}
//Don't let the player buy stock if they cannot afford it.
if(stockPrices[playerId].currentPrice.getAmount() > highestAffordablePrice){
buyStock[playerId].setEnabled(false);
}
}
//Enable and disable bond actions.
int outstandingBonds = thisDataGatherer.getBonds();
repayBondAction.setEnabled(outstandingBonds > 0);
issueBondAction.setEnabled(outstandingBonds < 4);
}
private void updateHtml() {
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal p = modelRoot.getPrincipal();
brokerScreenGenerator = new BrokerScreenGenerator(world, p);
// this is where the Menu get Enable and Disable by if you own any stock
// or if the TotalShares are 0
StringBuffer populatedTemplate = new StringBuffer();
populatedTemplate.append("<html>");
populatedTemplate
.append(populateTokens(template, brokerScreenGenerator));
for (int i = 0; i < world.getNumberOfPlayers(); i++) {
if (!(world.getPlayer(i).getPrincipal().equals(p))) {
BrokerScreenGenerator temp = new BrokerScreenGenerator(world,
world.getPlayer(i).getPrincipal());
populatedTemplate.append(populateTokens(template, temp));
}
}
populatedTemplate.append("</html>");
String html = populatedTemplate.toString();
setHtml(html);
enableAndDisableActions();
}
@Override
protected void paintComponent(Graphics g) {
/* Check to see if the text needs updating before painting. */
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
int currentNumberOfTransactions = world
.getNumberOfTransactions(playerPrincipal);
if (currentNumberOfTransactions != lastNumTransactions) {
updateHtml();
}
super.paintComponent(g);
}
}

TrainSummaryJPanel

Full name: jfreerails.client.view.TrainSummaryJPanel

Documentation

/**
*
* @author cphillips
*/

Source Code

/**
*
* @author cphillips
*/
public class TrainSummaryJPanel extends javax.swing.JPanel implements
ListCellRenderer, View {
private static final long serialVersionUID = 4121133628006020919L;
private jfreerails.world.top.ReadOnlyWorld w;
private FreerailsPrincipal principal;
private final Color backgroundColor = (java.awt.Color) javax.swing.UIManager
.getDefaults().get("List.background");
private final Color selectedColor = (java.awt.Color) javax.swing.UIManager
.getDefaults().get("List.selectionBackground");
private final Color selectedColorNotFocused = Color.LIGHT_GRAY;
private TrainListCellRenderer trainListCellRenderer1;
/** Creates new form TrainSummaryJPanel */
public TrainSummaryJPanel() {
initComponents();
}
public void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
this.principal = modelRoot.getPrincipal();
this.w = modelRoot.getWorld();
trainListCellRenderer1 = new TrainListCellRenderer(modelRoot, vl);
trainListCellRenderer1.setHeight(15);
}
private String findStationName(int trainNum) {
TrainOrdersModel orders = null;
TrainOrdersListModel ordersList = new TrainOrdersListModel(w, trainNum,
principal);
for (int i = 0; i < ordersList.getSize(); ++i) {
TrainOrdersListElement element = (TrainOrdersListElement) ordersList
.getElementAt(i);
if (element.gotoStatus == TrainOrdersListModel.GOTO_NOW) {
orders = element.order;
break;
}
}
StationModel station = (StationModel) w.get(principal, KEY.STATIONS, orders
.getStationID());
return station.getStationName();
}
private String findTrainIncome(int trainNum) {
IncomeStatementGenerator income = new IncomeStatementGenerator(w,
principal);
Money m = income.calTrainRevenue(trainNum);
return "$" + m.toString();
}
public java.awt.Component getListCellRendererComponent(
javax.swing.JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
int trainID = NonNullElements
.row2index(w, KEY.TRAINS, principal, index);
trainNumLabel.setText("#" + (trainID + 1));
headingLabel.setText(findStationName(trainID));
trainMaintenanceCostLabel.setText(findMaintenanceCost());
trainIncomeLabel.setText(findTrainIncome(trainID));
java.awt.GridBagConstraints gridBagConstraints;
trainListCellRenderer1.setOpaque(true);
trainListCellRenderer1.setCenterTrain(false);
trainListCellRenderer1.display(trainID);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(3, 0, 3, 0);
add(trainListCellRenderer1, gridBagConstraints);
if (isSelected) {
if (list.isFocusOwner()) {
setBackground(selectedColor);
trainListCellRenderer1.setBackground(selectedColor);
} else {
setBackground(selectedColorNotFocused);
trainListCellRenderer1.setBackground(selectedColorNotFocused);
}
} else {
setBackground(backgroundColor);
trainListCellRenderer1.setBackground(backgroundColor);
}
// Set selected
return this;
}
private String findMaintenanceCost() {
GameTime time = w.currentTime();
GameCalendar gameCalendar = (GameCalendar) w.get(ITEM.CALENDAR);
double month = gameCalendar.getMonth(time.getTicks());
long cost = (long) (month / 12 * 5000);
Money m = new Money(cost);
return "$" + m.toString();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
trainNumLabel = new javax.swing.JLabel();
headingLabel = new javax.swing.JLabel();
trainMaintenanceCostLabel = new javax.swing.JLabel();
trainIncomeLabel = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(500, 50));
trainNumLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
trainNumLabel.setText("jLabel1");
trainNumLabel
.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
trainNumLabel.setPreferredSize(new java.awt.Dimension(100, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
add(trainNumLabel, gridBagConstraints);
headingLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
headingLabel.setText("jLabel2");
headingLabel
.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
headingLabel.setPreferredSize(new java.awt.Dimension(100, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10);
add(headingLabel, gridBagConstraints);
trainMaintenanceCostLabel
.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
trainMaintenanceCostLabel.setText("jLabel3");
trainMaintenanceCostLabel.setMaximumSize(getMaximumSize());
trainMaintenanceCostLabel.setPreferredSize(new java.awt.Dimension(100,
25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10);
add(trainMaintenanceCostLabel, gridBagConstraints);
trainIncomeLabel
.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
trainIncomeLabel.setText("jLabel1");
trainIncomeLabel.setPreferredSize(new java.awt.Dimension(100, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
add(trainIncomeLabel, gridBagConstraints);
}// GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel headingLabel;
private javax.swing.JLabel trainIncomeLabel;
private javax.swing.JLabel trainMaintenanceCostLabel;
private javax.swing.JLabel trainNumLabel;
// End of variables declaration//GEN-END:variables
}

ActionAdapter

Full name: jfreerails.client.common.ActionAdapter

Documentation

/**
* Provides a mapping from a set of ButtonModels or a ComboBoxModel to a set of
* Actions. To use with a set of buttons, call elements() to obtain the set of
* ButtonModels to apply to the buttons, and add each button in the enumeration
* to a ButtonGroup. Listeners should listen for changes to the model and not to
* any events from UI components, although UI components may call setAction() in
* order to receive property change updates and to set icons etc.
*
* @author Rob
*/

Source Code

/**
* Provides a mapping from a set of ButtonModels or a ComboBoxModel to a set of
* Actions. To use with a set of buttons, call elements() to obtain the set of
* ButtonModels to apply to the buttons, and add each button in the enumeration
* to a ButtonGroup. Listeners should listen for changes to the model and not to
* any events from UI components, although UI components may call setAction() in
* order to receive property change updates and to set icons etc.
*
* @author Rob
*/
public class ActionAdapter extends DefaultComboBoxModel {
private static final long serialVersionUID = 3546920294666351415L;
/**
* The set of actions which each button / menu item correspond to.
*/
private final Action[] actions;
private boolean initialised = false;
private boolean performActionOnSetSelectedItem = true;
/**
* The set of MappedButtonModels corresponding to the actions.
*/
private final Vector<MappedButtonModel> buttonModels;
/**
* An array of the actions to be used. The ComboBoxModel objects are taken
* from the NAME property of the Action. The ButtonModel icons are obtained
* from the SMALL_ICON property.
*/
public ActionAdapter(Action[] actions) {
super();
this.actions = actions;
buttonModels = new Vector<MappedButtonModel>();
for (int i = 0; i < actions.length; i++) {
buttonModels.add(new MappedButtonModel(actions[i]));
addElement(actions[i].getValue(Action.NAME));
}
initialised = true;
}
/**
* @param actions
* An array of the actions to be used. The ComboBoxModel objects
* are taken from the NAME property of the Action. The
* ButtonModel icons are obtained from the SMALL_ICON property.
* @param selected
* Index of the default selected action.
*/
public ActionAdapter(Action[] actions, int selected) {
this(actions);
for (int i = 0; i < buttonModels.size(); i++) {
MappedButtonModel bm = buttonModels.get(i);
bm.setSelected(i == selected);
}
}
/**
* @return an enumeration of Action
*/
public Enumeration<Action> getActions() {
return new Enumeration<Action>() {
private int i = 0;
public boolean hasMoreElements() {
return (i < actions.length);
}
public Action nextElement() {
return actions[i++];
}
};
}
/**
* @return an enumeration of MappedButtonModel
*/
public Enumeration<MappedButtonModel> getButtonModels() {
return buttonModels.elements();
}
/**
* @param item
* The NAME of the Action selected
*/
@Override
public void setSelectedItem(Object item) {
// only set the item if not already selected
if ((item != null) && item.equals(getSelectedItem())) {
return;
}
super.setSelectedItem(item);
// stop addElement from triggering actions
if (!initialised) {
return;
}
for (int i = 0; i < buttonModels.size(); i++) {
MappedButtonModel bm = buttonModels.get(i);
if (bm.actionName.equals(item)) {
bm.setSelected(true);
}
}
if (performActionOnSetSelectedItem) {
for (int i = 0; i < actions.length; i++) {
if (actions[i].getValue(Action.NAME).equals(item)) {
actions[i].actionPerformed(new ActionEvent(this,
ActionEvent.ACTION_PERFORMED, (String) actions[i]
.getValue(Action.ACTION_COMMAND_KEY)));
}
}
}
}
public class MappedButtonModel extends JToggleButton.ToggleButtonModel
implements PropertyChangeListener {
private static final long serialVersionUID = 3834589889856353845L;
/**
* The NAME of the Action to which this ButtonModel is mapped.
*/
public final String actionName;
public MappedButtonModel(Action action) {
actionName = (String) action.getValue(Action.NAME);
action.addPropertyChangeListener(this);
setEnabled(action.isEnabled());
}
@Override
public void setSelected(boolean b) {
if (isSelected() != b) {
super.setSelected(b);
if (b) {
ActionAdapter.this.setSelectedItem(actionName);
}
}
}
public void propertyChange(PropertyChangeEvent e) {
setEnabled(((Action) e.getSource()).isEnabled());
}
}
public void setPerformActionOnSetSelectedItem(
boolean performActionOnSetSelectedItem) {
this.performActionOnSetSelectedItem = performActionOnSetSelectedItem;
}
}

ImageManagerImpl

Full name: jfreerails.client.common.ImageManagerImpl

Documentation

/**
* Implementation of ImageManager that returns images that are compatible with
* the current graphics configuration and whose transparency is set to
* TRANSLUCENT, the scaled images it returns are rendered with renderingHints
* set for quality.
*
* @author Luke
*
*/

Source Code

/**
* Implementation of ImageManager that returns images that are compatible with
* the current graphics configuration and whose transparency is set to
* TRANSLUCENT, the scaled images it returns are rendered with renderingHints
* set for quality.
*
* @author Luke
*
*/
public class ImageManagerImpl implements ImageManager {
/**
* Matches anying but a string beginning with a "/"*. The reason for this
* check is that relative filenames such as "/cursor/removetrack.png" work
* from with files but not from within jars, which lets bugs slip in.
*/
private static final String A_REGEX = "^[^///].*";
private static final Logger logger = Logger
.getLogger(ImageManagerImpl.class.getName());
private static final Pattern pattern = Pattern.compile(A_REGEX);
public static boolean isValid(String s) {
Matcher m = pattern.matcher(s);
return m.matches();
}
private final GraphicsConfiguration defaultConfiguration = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
private final HashMap<String, Image> imageHashMap = new HashMap<String, Image>();
private String pathToReadFrom;
private String pathToWriteTo;
private final RenderingHints renderingHints;
private final HashMap<String, Image> scaledImagesHashMap = new HashMap<String, Image>();
public ImageManagerImpl(String readpath) {
this(readpath, null);
}
public ImageManagerImpl(String readpath, String writePath) {
pathToReadFrom = readpath;
pathToWriteTo = writePath;
// Attempt to increase quality..
renderingHints = new RenderingHints(
RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
renderingHints.put(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
renderingHints.put(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
}
public boolean contains(String relativeFilename) {
relativeFilename = relativeFilename.replace(' ', '_');
if (imageHashMap.containsKey(relativeFilename)) {
return true;
}
File f = new File(pathToWriteTo + File.separator + relativeFilename);
if (f.isFile()) {
return true;
}
return false;
}
public Image getImage(String relativeFilename) throws IOException {
relativeFilename = relativeFilename.replace(' ', '_');
if (!isValid(relativeFilename))
throw new IllegalArgumentException(relativeFilename
+ " must match " + A_REGEX);
if (imageHashMap.containsKey(relativeFilename)) {
return imageHashMap.get(relativeFilename);
}
// File f = new File(pathToReadFrom+File.separator+relativeFilename);
String read = pathToReadFrom + relativeFilename;
read = read.replace(File.separatorChar, '/');
URL url = ImageManagerImpl.class.getResource(read);
if (null == url) {
throw new IOException("Couldn't find: " + read);
}
Image tempImage = ImageIO.read(url);
if (null == tempImage) {
throw new IOException("Couldn't find: " + read);
}
Image compatibleImage = defaultConfiguration.createCompatibleImage(
tempImage.getWidth(null), tempImage.getHeight(null),
Transparency.TRANSLUCENT);
Graphics g = compatibleImage.getGraphics();
g.drawImage(tempImage, 0, 0, null);
imageHashMap.put(relativeFilename, compatibleImage);
return compatibleImage;
}
/**
* Returns the specified image scaled so that its height is equal to the
* specified height.
*/
public Image getScaledImage(String relativeFilename, int height)
throws IOException {
relativeFilename = relativeFilename.replace(' ', '_');
if (!isValid(relativeFilename))
throw new IllegalArgumentException(relativeFilename
+ " must match " + A_REGEX);
String hashKey = relativeFilename + height;
if (this.scaledImagesHashMap.containsKey(hashKey)) {
return scaledImagesHashMap.get(hashKey);
}
Image i = getImage(relativeFilename);
if (i.getHeight(null) == height) {
return i;
}
int width = (i.getWidth(null) * height) / i.getHeight(null);
Image compatibleImage = newBlankImage(height, width);
Graphics2D g = (Graphics2D) compatibleImage.getGraphics();
g.setRenderingHints(this.renderingHints);
g.drawImage(i, 0, 0, width, height, null);
scaledImagesHashMap.put(hashKey, compatibleImage);
return compatibleImage;
}
public Image newBlankImage(int height, int width) {
Image compatibleImage = defaultConfiguration.createCompatibleImage(
width, height, Transparency.TRANSLUCENT);
return compatibleImage;
}
public void setImage(String relativeFilename, Image i) {
relativeFilename = relativeFilename.replace(' ', '_');
if (i == null) {
throw new NullPointerException(relativeFilename);
}
imageHashMap.put(relativeFilename, i);
}
public void setPathToReadFrom(String s) {
pathToReadFrom = s;
}
public void setPathToWriteTo(String s) {
pathToWriteTo = s;
}
public void writeAllImages() throws IOException {
for (String s : imageHashMap.keySet()) {
writeImage(s);
}
}
public void writeImage(String relativeFilename) throws IOException {
if (null == pathToWriteTo)
throw new NullPointerException("null == pathToWriteTo");
relativeFilename = relativeFilename.replace(' ', '_');
File f = new File(pathToWriteTo + File.separator + relativeFilename);
if (imageHashMap.containsKey(relativeFilename)) {
RenderedImage i = (RenderedImage) imageHashMap
.get(relativeFilename);
String pathName = f.getPath();
File path = new File(pathName);
path.mkdirs();
ImageIO.write(i, "png", f);
logger.info("Writing " + f);
} else {
throw new NoSuchElementException(relativeFilename);
}
}
}

ModelRootImpl

Full name: jfreerails.client.common.ModelRootImpl

Documentation

/**
* Provides access to the World object and other data that is shared by GUI
* components (for instance the cursor's position).
*
* @author Luke
* @author Rob
*/

Source Code

/**
* Provides access to the World object and other data that is shared by GUI
* components (for instance the cursor's position).
*
* @author Luke
* @author Rob
*/
public final class ModelRootImpl implements ModelRoot, ServerCommandReceiver {
public boolean hasBeenSetup = false;
private MoveChainFork moveFork = new MoveChainFork();
private UntriedMoveReceiver moveReceiver = new UntriedMoveReceiver() {
public void processMove(Move Move) {
}
public void processPreMove(PreMove pm) {
}
public MoveStatus tryDoMove(Move move) {
return MoveStatus.moveFailed("No move receiver set on model root!");
}
};
private FreerailsPrincipal playerPrincipal;
private final HashMap<Property, Object> properties = new HashMap<Property, Object>();
private ServerCommandReceiver serverCommandReceiver;
private ReadOnlyWorld world;
private final ArrayList<ModelRootListener> listeners = new ArrayList<ModelRootListener>();
public ModelRootImpl() {
properties.put(Property.CURSOR_POSITION, new ImPoint());
properties.put(Property.SHOW_STATION_NAMES, Boolean.TRUE);
properties.put(Property.SHOW_CARGO_AT_STATIONS, Boolean.TRUE);
properties.put(Property.SHOW_STATION_BORDERS, Boolean.TRUE);
properties.put(Property.CURSOR_MODE, Value.BUILD_TRACK_CURSOR_MODE);
properties.put(Property.PREVIOUS_CURSOR_MODE,
Value.BUILD_TRACK_CURSOR_MODE);
properties.put(Property.SERVER, "server details not set!");
properties.put(Property.PLAY_SOUNDS, Boolean.TRUE);
properties.put(Property.IGNORE_KEY_EVENTS, Boolean.FALSE);
properties.put(Property.TIME, new Double(0));
properties.put(Property.TRACK_BUILDER_MODE,
TrackMoveProducer.BuildMode.BUILD_TRACK);
properties.put(Property.SAVED_GAMES_LIST, new ImStringList());
addPropertyChangeListener(SoundManager.getSoundManager());
}
public void addCompleteMoveReceiver(MoveReceiver l) {
this.moveFork.addCompleteMoveReceiver(l);
}
public void addListListener(WorldListListener listener) {
this.moveFork.addListListener(listener);
}
public void addMapListener(WorldMapListener l) {
this.moveFork.addMapListener(l);
}
public void addPropertyChangeListener(ModelRootListener l) {
listeners.add(l);
}
public void addSplitMoveReceiver(MoveReceiver l) {
this.moveFork.addSplitMoveReceiver(l);
}
public MoveStatus doMove(Move m) {
MoveStatus ms = this.moveReceiver.tryDoMove(m);
this.moveReceiver.processMove(m);
return ms;
}
public MoveStatus doPreMove(PreMove pm) {
Move m = pm.generateMove(world);
MoveStatus ms = moveReceiver.tryDoMove(m);
moveReceiver.processPreMove(pm);
return ms;
}
public FreerailsPrincipal getPrincipal() {
if (null == playerPrincipal) {
throw new NullPointerException();
}
return playerPrincipal;
}
public Object getProperty(Property p) {
return properties.get(p);
}
public ReadOnlyWorld getWorld() {
return world;
}
public void sendCommand(Message2Server c) {
if (null != serverCommandReceiver) {
serverCommandReceiver.sendCommand(c);
} else {
System.err.println(c.toString());
}
}
public void setMoveFork(MoveChainFork moveFork) {
this.moveFork = moveFork;
}
public void setMoveReceiver(UntriedMoveReceiver moveReceiver) {
this.moveReceiver = moveReceiver;
}
public void setProperty(Property p, Object newValue) {
Object oldValue = properties.get(p);
properties.put(p, newValue);
for (ModelRootListener listener : listeners) {
listener.propertyChange(p, oldValue, newValue);
}
}
public void setServerCommandReceiver(
ServerCommandReceiver serverCommandReceiver) {
this.serverCommandReceiver = serverCommandReceiver;
}
/**
* Updates the ModelRoot with those properties which are dependent upon the
* world model. Call this when the world model is changed (e.g. new map is
* loaded)
*/
public void setup(ReadOnlyWorld world, FreerailsPrincipal p) {
this.world = world;
assert p != null;
assert world.isPlayer(p);
playerPrincipal = p;
if (null == world) {
throw new NullPointerException();
}
BuildTrackStrategy bts = BuildTrackStrategy.getDefault(world);
setProperty(ModelRoot.Property.BUILD_TRACK_STRATEGY, bts);
hasBeenSetup = true;
}
public MoveStatus tryDoMove(Move m) {
return this.moveReceiver.tryDoMove(m);
}
public boolean is(ModelRoot.Property p, Object value) {
return getProperty(p).equals(value);
}
}

BinaryNumberFormatter

Full name: jfreerails.client.common.BinaryNumberFormatter

Documentation

/**
* Used to generate filenames for track and terrain images.
*
* @author Luke
*/

Source Code

/**
* Used to generate filenames for track and terrain images.
*
* @author Luke
*/
public class BinaryNumberFormatter {
public static String format(int i, int bits) {
int maxValue = 1 << (bits);
if (i < 0) {
throw new IllegalArgumentException(
"i must be greater than 0. It was " + i);
}
if (i >= maxValue) {
throw new IllegalArgumentException("i must be less than "
+ maxValue + ". It was " + i);
}
String s = Integer.toString(i + maxValue, 2);
String number = s.substring(1);
return number;
}
public static String formatWithLowBitOnLeft(int i, int bits) {
StringBuffer buff = new StringBuffer(format(i, bits));
buff.reverse();
return buff.toString();
}
}

MyGlassPanel

Full name: jfreerails.client.common.MyGlassPanel

Documentation

/**
* A transparent JPanel that catches key presses and mouse clicks.
*
* @author lindsal8
*
*/

Source Code

/**
* A transparent JPanel that catches key presses and mouse clicks.
*
* @author lindsal8
*
*/
public class MyGlassPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 3976735856986239795L;
public MyGlassPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() { // GEN-BEGIN:initComponents
contentPanel = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
java.awt.GridBagConstraints gridBagConstraints1;
setOpaque(false);
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mousePressed(java.awt.event.MouseEvent evt) {
formMousePressed(evt);
}
});
addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
@Override
public void mouseMoved(java.awt.event.MouseEvent evt) {
formMouseMoved(evt);
}
});
contentPanel.setPreferredSize(new java.awt.Dimension(60, 40));
contentPanel.setMinimumSize(new java.awt.Dimension(60, 40));
contentPanel.setBackground(java.awt.Color.red);
contentPanel.setMaximumSize(new java.awt.Dimension(60, 40));
gridBagConstraints1 = new java.awt.GridBagConstraints();
gridBagConstraints1.gridx = 2;
gridBagConstraints1.gridy = 1;
add(contentPanel, gridBagConstraints1);
}
// GEN-END:initComponents
private void formMouseMoved(java.awt.event.MouseEvent evt) { // GEN-FIRST:event_formMouseMoved
// Add your handling code here:
}
// GEN-LAST:event_formMouseMoved
private void formMousePressed(java.awt.event.MouseEvent evt) { // GEN-FIRST:event_formMousePressed
// Add your handling code here:
}
// GEN-LAST:event_formMousePressed
private void formKeyPressed(java.awt.event.KeyEvent evt) { // GEN-FIRST:event_formKeyPressed
// Add your handling code here:
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComponent contentPanel;
// End of variables declaration//GEN-END:variables
}

Painter

Full name: jfreerails.client.common.Painter

Documentation

/**
* Paints a layer of the map view.
*
* @author Luke
*/

Source Code

/**
* Paints a layer of the map view.
*
* @author Luke
*/
public interface Painter {
void paint(Graphics2D g);
}

Methods

ModelRootListener

Full name: jfreerails.client.common.ModelRootListener

Documentation

/**
* @author Luke
*
*/

Source Code

/**
* @author Luke
*
*/
public interface ModelRootListener {
void propertyChange(ModelRoot.Property p, Object oldValue, Object newValue);
}

Methods

SoundManager

Full name: jfreerails.client.common.SoundManager

Documentation

/**
* This class is responsible for loading and playing sounds. Samples are read
* into a byte arrays so that they don't need to be loaded from disk each time
* they are played.
*
* @author Luke
*
*/

Source Code

/**
* This class is responsible for loading and playing sounds. Samples are read
* into a byte arrays so that they don't need to be loaded from disk each time
* they are played.
*
* @author Luke
*
*/
public class SoundManager implements ModelRootListener, LineListener {
/**
* Stores the audio data and properties of a sample.
*
*/
private static class Sample {
byte[] audio;
AudioFormat format;
DataLine.Info info;
int size;
}
private static final Logger logger = Logger.getLogger(SoundManager.class
.getName());
private static final SoundManager soundManager = new SoundManager();
public static SoundManager getSoundManager() {
return soundManager;
}
public static void main(String[] args) {
SoundManager soundPlayer = getSoundManager();
for (int i = 0; i < 100; i++) {
soundPlayer.playSound("/jfreerails/client/sounds/cash.wav", 10);
try {
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private int maxLines;
private Mixer mixer;
private boolean playSounds = true;
private HashMap<String, Sample> samples = new HashMap<String, Sample>();
private final LinkedList<Clip> voices = new LinkedList<Clip>();
private SoundManager() {
AudioFormat format2 = new AudioFormat(8000f, 16, 1, true, false);
DataLine.Info info2 = new DataLine.Info(Clip.class, format2);
for (Mixer.Info mo : AudioSystem.getMixerInfo()) {
mixer = AudioSystem.getMixer(mo);
maxLines = mixer.getMaxLines(info2);
if (maxLines == AudioSystem.NOT_SPECIFIED){
maxLines = 100;
}
if (maxLines >= 32)
break; // Java Sound Audio Engine, version 1.0 satisfies this.
}
logger.fine("Sound Mixer: " + mixer.getMixerInfo() + "(" + maxLines
+ " voices).");
}
public void addClip(String s) throws IOException,
UnsupportedAudioFileException, LineUnavailableException {
if (samples.containsKey(s)) {
return;
}
URL url = getClass().getResource(s);
AudioInputStream audioInputStream = AudioSystem
.getAudioInputStream(loadStream(url.openStream()));
Sample sample = new Sample();
sample.format = audioInputStream.getFormat();
sample.size = (int) (sample.format.getFrameSize() * audioInputStream
.getFrameLength());
sample.audio = new byte[sample.size];
sample.info = new DataLine.Info(Clip.class, sample.format, sample.size);
audioInputStream.read(sample.audio, 0, sample.size);
samples.put(s, sample);
}
private ByteArrayInputStream loadStream(InputStream inputstream)
throws IOException {
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
for (int i = inputstream.read(data); i != -1; i = inputstream
.read(data)) {
bytearrayoutputstream.write(data, 0, i);
}
inputstream.close();
bytearrayoutputstream.close();
data = bytearrayoutputstream.toByteArray();
return new ByteArrayInputStream(data);
}
public void playSound(String s, int loops) {
if (playSounds) {
try {
if (!samples.containsKey(s)) {
addClip(s);
}
Sample sample = samples.get(s);
Clip clip;
if (voices.size() < maxLines) {
clip = (Clip) mixer.getLine(sample.info);
} else {
clip = voices.removeFirst();
clip.stop();
clip.flush();
clip.close();
}
clip.addLineListener(this);
clip.open(sample.format, sample.audio, 0, sample.size);
clip.loop(loops);
voices.add(clip);
} catch (LineUnavailableException e) {
logger.warning(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void propertyChange(ModelRoot.Property p, Object before, Object after) {
if (p.equals(ModelRoot.Property.PLAY_SOUNDS)) {
Boolean b = (Boolean) after;
playSounds = b.booleanValue();
}
}
public void update(LineEvent event) {
// TODO free up resources when we have finished playing a clip.
}
}

ImageManager

Full name: jfreerails.client.common.ImageManager

Documentation

/**
* This interface defines methods for loading and saving images, and producing
* scaled images whose quality may be controlled.
*
* @author Luke
*
*/

Source Code

/**
* This interface defines methods for loading and saving images, and producing
* scaled images whose quality may be controlled.
*
* @author Luke
*
*/
public interface ImageManager {
Image newBlankImage(int height, int width);
void setPathToReadFrom(String s);
void setPathToWriteTo(String s);
Image getImage(String relativeFilename) throws IOException;
boolean contains(String relativeFilename);
void setImage(String relativeFilename, Image i);
void writeImage(String relativeFilename) throws IOException;
void writeAllImages() throws IOException;
Image getScaledImage(String relativeFilename, int height)
throws IOException;
}

RepaintManagerForActiveRendering

Full name: jfreerails.client.common.RepaintManagerForActiveRendering

Documentation

/**
* This RepaintManager is intended to be used when we are using active rendering
* to paint a top level component. Repaint requests for components whose
* TopLevelAncestor is the component being actively rendered in the game loop
* are ignored; repaint requests for components whose TopLevelAncestor is
* <strong>not</strong> the component being actively rendered in the game loop
* are processed normally. This behaviour is needed because when menus extend
* outside the bounds of their parent window, they have a different top level
* component to the parent window, so are not painted when paintComponents is
* called from the game loop.
*
* @author Luke
*
*/

Source Code

/**
* This RepaintManager is intended to be used when we are using active rendering
* to paint a top level component. Repaint requests for components whose
* TopLevelAncestor is the component being actively rendered in the game loop
* are ignored; repaint requests for components whose TopLevelAncestor is
* <strong>not</strong> the component being actively rendered in the game loop
* are processed normally. This behaviour is needed because when menus extend
* outside the bounds of their parent window, they have a different top level
* component to the parent window, so are not painted when paintComponents is
* called from the game loop.
*
* @author Luke
*
*/
public final class RepaintManagerForActiveRendering extends RepaintManager {
/** The JFrame(s) that are being actively rendered in the game loop(s). */
private static final HashSet<JFrame> activelyRenderedComponents = new HashSet<JFrame>();
private static final RepaintManagerForActiveRendering instance = new RepaintManagerForActiveRendering();
private static long numRepaintRequests = 0;
public static void setAsCurrentManager() {
RepaintManager.setCurrentManager(instance);
}
private RepaintManagerForActiveRendering() {
}
@Override
public synchronized void addDirtyRegion(JComponent c, int x, int y, int w,
int h) {
if (hasDifferentAncestor(c)) {
super.addDirtyRegion(c, x, y, w, h);
} else {
numRepaintRequests++;
}
}
public static synchronized void addJFrame(JFrame f) {
activelyRenderedComponents.add(f);
}
@Override
public synchronized void addInvalidComponent(JComponent invalidComponent) {
if (hasDifferentAncestor(invalidComponent)) {
super.addInvalidComponent(invalidComponent);
} else {
numRepaintRequests++;
}
}
@Override
public void markCompletelyClean(JComponent aComponent) {
if (hasDifferentAncestor(aComponent)) {
super.markCompletelyClean(aComponent);
} else {
numRepaintRequests++;
}
}
@Override
public void markCompletelyDirty(JComponent aComponent) {
if (hasDifferentAncestor(aComponent)) {
super.markCompletelyDirty(aComponent);
} else {
numRepaintRequests++;
}
}
private boolean hasDifferentAncestor(JComponent aComponent) {
Container topLevelAncestor = aComponent.getTopLevelAncestor();
if (null == topLevelAncestor
|| activelyRenderedComponents.contains(topLevelAncestor)) {
return false;
}
return true;
}
public static long getNumRepaintRequests() {
return numRepaintRequests;
}
}

TileRendererList

Full name: jfreerails.client.renderer.TileRendererList

Documentation

/**
* A list of TileRenderers.
*
* @author Luke Lindsay 09 October 2001
*/

Source Code

/**
* A list of TileRenderers.
*
* @author Luke Lindsay 09 October 2001
*/
public interface TileRendererList {
TileRenderer getTileViewWithNumber(int i);
/**
* Checks whether this tile view list has tile views for all the terrain
* types in the specified list.
*/
boolean validate(ReadOnlyWorld world);
}

BuildTrackController

Full name: jfreerails.client.renderer.BuildTrackController

Documentation

/**
* This class provides methods to change the proposed track and save it to the
* real world.
*
* TODO jfreerails.client.renderer is not the most logical place for this class.
*
* @author MystiqueAgent
* @author Luke
*
*/

Source Code

/**
* This class provides methods to change the proposed track and save it to the
* real world.
*
* TODO jfreerails.client.renderer is not the most logical place for this class.
*
* @author MystiqueAgent
* @author Luke
*
*/
public class BuildTrackController implements GameModel {
private static final Logger LOGGER = Logger
.getLogger(BuildTrackController.class.getName());
private boolean buildNewTrack = true;
private List<ImPoint> builtTrack = new ArrayList<ImPoint>();
private boolean isBuildTrackSuccessful = false;
private final ModelRoot modelRoot;
private Step[] path;
private TrackPathFinder path4newTrackFinder;
private PathOnTrackFinder pathOnExistingTrackFinder;
private FreerailsPrincipal principal;
private ReadOnlyWorld realWorld;
private SoundManager soundManager = SoundManager.getSoundManager();
private ImPoint startPoint;
private ImPoint targetPoint;
private boolean visible = false;
private WorldDiffs worldDiffs;
/**
* BuildTrackRenderer
*
* @param readOnlyWorld
* ReadOnlyWorld
*/
public BuildTrackController(ReadOnlyWorld readOnlyWorld, ModelRoot modelRoot) {
worldDiffs = new WorldDiffs(readOnlyWorld);
realWorld = readOnlyWorld;
path4newTrackFinder = new TrackPathFinder(readOnlyWorld, modelRoot
.getPrincipal());
pathOnExistingTrackFinder = new PathOnTrackFinder(readOnlyWorld);
this.modelRoot = modelRoot;
principal = modelRoot.getPrincipal();
setWorldDiffs(worldDiffs);
}
/** Utility method that gets the BuildTrackStrategy from the model root. */
private BuildTrackStrategy getBts() {
BuildTrackStrategy btss = (BuildTrackStrategy) modelRoot
.getProperty(ModelRoot.Property.BUILD_TRACK_STRATEGY);
if (null == btss)
throw new NullPointerException();
return btss;
}
/** Utility method that gets the cursor position from the model root. */
private ImPoint getCursorPosition() {
ImPoint point = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.CURSOR_POSITION);
// Check for null & make a defensive copy
point = null == point ? new ImPoint() : point;
if (!modelRoot.getWorld().boundsContain(point.x, point.y)) {
throw new IllegalStateException(String.valueOf(point));
}
return point;
}
/** Hides and cancels any proposed track. */
public void hide() {
this.setVisible(false);
setTargetPoint(null);
reset();
}
/**
* returns <code>true</code> if the track is being build - it is iff the
* build track is shown
*
* @return boolean
*/
public boolean isBuilding() {
return visible;
}
/** Returns true if all the track pieces can be successfully built. */
public boolean isBuildTrackSuccessful() {
return isBuildTrackSuccessful;
}
/** Moves cursor which causes track to be built on the worldDiff object. */
private void moveCursorMoreTiles(List<ImPoint> track) {
moveCursorMoreTiles(track, null);
}
/**
* uses <code>trackBuilder</code> if not null -- otherwise uses own
* <code>buildTrack</code> method - that is applied on
* <code>worldDifferences</code>
*
* @param track
* List
* @param trackBuilder
* TrackMoveProducer
*/
private MoveStatus moveCursorMoreTiles(List<ImPoint> track,
TrackMoveProducer trackBuilder) {
ImPoint oldPosition = getCursorPosition();
if(!Step.checkValidity(oldPosition, track.get(0))){
throw new IllegalStateException(oldPosition.toString()+ " and "+track.get(0).toString());
}
MoveStatus ms = null;
int piecesOfNewTrack = 0;
if (null != trackBuilder) {
trackBuilder.setBuildTrackStrategy(getBts());
}
for (Iterator<ImPoint> iter = track.iterator(); iter.hasNext();) {
ImPoint point = iter.next();
LOGGER.fine("point" + point);
LOGGER.fine("oldPosition" + oldPosition);
if (oldPosition.equals(point)) {
LOGGER.fine("(oldPosition.equals(point))" + point);
continue;
}
Step vector = Step.getInstance(point.x - oldPosition.x, point.y
- oldPosition.y);
// If there is already track between the two tiles, do nothing
FreerailsTile tile = (FreerailsTile) realWorld.getTile(
oldPosition.x, oldPosition.y);
if (tile.getTrackPiece().getTrackConfiguration().contains(vector)) {
oldPosition = point;
continue;
}
piecesOfNewTrack++;
if (trackBuilder != null) {
ms = trackBuilder.buildTrack(oldPosition, vector);
} else {
ms = planBuildingTrack(oldPosition, vector);
}
if (ms.ok) {
setCursorMessage("");
} else {
setCursorMessage(ms.message);
reset();
return ms;
}
oldPosition = point;
}
/* Check whether there is already track at every point. */
if (piecesOfNewTrack == 0) {
MoveStatus moveFailed = MoveStatus.moveFailed("Track already here");
setCursorMessage(moveFailed.message);
return moveFailed;
}
isBuildTrackSuccessful = true;
// If track has actually been built, play the build track sound.
if (trackBuilder != null && ms.isOk()) {
if (trackBuilder.getTrackBuilderMode() == BUILD_TRACK) {
this.soundManager.playSound(
"/jfreerails/client/sounds/buildtrack.wav", 0);
}
}
return ms;
}
/**
* Attempts to building track from the specified point in the specified
* direction on the worldDiff object.
*/
private MoveStatus planBuildingTrack(ImPoint point, Step vector) {
FreerailsTile tileA = (FreerailsTile) worldDiffs.getTile(point.x,
point.y);
BuildTrackStrategy bts = getBts();
int trackTypeAID = bts.getRule(tileA.getTerrainTypeID());
TrackRule trackRuleA = (TrackRule) worldDiffs.get(SKEY.TRACK_RULES,
trackTypeAID);
FreerailsTile tileB = (FreerailsTile) worldDiffs.getTile(point.x
+ vector.deltaX, point.y + vector.deltaY);
int trackTypeBID = bts.getRule(tileB.getTerrainTypeID());
TrackRule trackRuleB = (TrackRule) worldDiffs.get(SKEY.TRACK_RULES,
trackTypeBID);
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(point, vector, trackRuleA, trackRuleB,
worldDiffs, principal);
return move.doMove(worldDiffs, principal);
}
/** Cancels any proposed track and resets the path finder. */
private void reset() {
worldDiffs.reset();
path4newTrackFinder.abandonSearch();
this.builtTrack.clear();
this.isBuildTrackSuccessful = false;
}
int searchStatus() {
if (buildNewTrack) {
return path4newTrackFinder.getStatus();
}
return pathOnExistingTrackFinder.getStatus();
}
/** Utility method that sets the CURSOR_MESSAGE property on the model root. */
private void setCursorMessage(String s) {
modelRoot.setProperty(ModelRoot.Property.CURSOR_MESSAGE, s);
}
/** Sets the proposed track: from the current cursor position to the specified point.*/
public void setProposedTrack(ImPoint to,
TrackMoveProducer trackBuilder) {
ImPoint from = getCursorPosition();
assert (trackBuilder.getTrackBuilderMode() != IGNORE_TRACK);
assert (trackBuilder.getTrackBuilderMode() != BUILD_STATION);
buildNewTrack = trackBuilder.getTrackBuilderMode() == BUILD_TRACK;
/*
* If we have just found the route between the two points, don't waste
* time doing it again.
*/
if (null != targetPoint && null != startPoint
&& targetPoint.equals(to)
&& startPoint.equals(from)
&& searchStatus() != IncrementalPathFinder.SEARCH_NOT_STARTED) {
return;
}
worldDiffs.reset();
builtTrack.clear();
isBuildTrackSuccessful = false;
if (from.equals(to)) {
hide();
return;
}
/* Check both points are on the map. */
if (!realWorld.boundsContain(from.x, from.y)
|| !realWorld.boundsContain(to.x, to.y)) {
hide();
return;
}
setTargetPoint(to);
startPoint = from;
try {
BuildTrackStrategy bts = getBts();
if (buildNewTrack) {
path4newTrackFinder.setupSearch(from, to, bts);
} else {
pathOnExistingTrackFinder.setupSearch(from, to);
}
} catch (PathNotFoundException e) {
setCursorMessage(e.getMessage());
return;
}
updateSearch();
}
/**
* @param newTargetPoint
* The m_targetPoint to set.
*/
private void setTargetPoint(ImPoint newTargetPoint) {
this.targetPoint = newTargetPoint;
ImPoint p = null == newTargetPoint ? null : newTargetPoint;
modelRoot.setProperty(ModelRoot.Property.THINKING_POINT, p);
}
private void setVisible(boolean show) {
if (show == visible) {
return;
}
if (show) {
setWorldDiffs(worldDiffs);
} else {
setWorldDiffs(null);
}
this.visible = show;
}
private void setWorldDiffs(WorldDiffs worldDiffs) {
modelRoot.setProperty(ModelRoot.Property.PROPOSED_TRACK, worldDiffs);
}
public void show() {
this.setVisible(true);
}
public void update() {
// update search for path if necessary.
if (searchStatus() == IncrementalPathFinder.SEARCH_PAUSED) {
updateSearch();
}
}
public void updateUntilComplete() {
while (searchStatus() != IncrementalPathFinder.PATH_FOUND) {
updateSearch();
}
}
/**
* Updates the search, if the search is completed, the proposed track is
* shown.
*/
private void updateSearch() {
try {
if (buildNewTrack) {
path4newTrackFinder.search(100);
} else {
pathOnExistingTrackFinder.search(100);
}
} catch (PathNotFoundException e) {
setCursorMessage(e.getMessage());
return;
}
if (searchStatus() == IncrementalPathFinder.PATH_FOUND) {
if (buildNewTrack) {
builtTrack = path4newTrackFinder.pathAsPoints();
moveCursorMoreTiles(builtTrack);
} else {
boolean okSoFar = true;
path = pathOnExistingTrackFinder.pathAsVectors();
TrackMoveProducer.BuildMode mode = getBuildMode();
int locationX = startPoint.x;
int locationY = startPoint.y;
FreerailsPrincipal fp = modelRoot.getPrincipal();
for (Step v : path) {
Move move;
attemptMove: {
switch (mode) {
case REMOVE_TRACK:
try {
move = ChangeTrackPieceCompositeMove
.generateRemoveTrackMove(new ImPoint(
locationX, locationY), v,
worldDiffs, fp);
break;
} catch (Exception e1) {
e1.printStackTrace();
break attemptMove;
}
case UPGRADE_TRACK:
int owner = ChangeTrackPieceCompositeMove.getOwner(
fp, worldDiffs);
FreerailsTile tile = (FreerailsTile) worldDiffs
.getTile(locationX, locationY);
int tt = tile.getTerrainTypeID();
int trackRuleID = getBts().getRule(tt);
/*
* Skip tiles that already have the right track
* type.
*/
if (trackRuleID == tile.getTrackPiece().getTrackTypeID()) {
break attemptMove;
}
TrackRule trackRule = (TrackRule) worldDiffs.get(
SKEY.TRACK_RULES, trackRuleID);
TrackPiece after = new TrackPieceImpl(tile
.getTrackPiece().getTrackConfiguration(), trackRule, owner,
trackRuleID);
/*
* We don't want to 'upgrade' a station to track.
* See bug 874416.
*/
if (tile.getTrackPiece().getTrackRule().isStation()) {
break attemptMove;
}
move = UpgradeTrackMove.generateMove(tile
.getTrackPiece(), after, new ImPoint(
locationX, locationY));
break;
default:
throw new IllegalStateException(mode.toString());
}// end of switch statement
MoveStatus ms = move.doMove(worldDiffs, fp);
okSoFar = ms.ok && okSoFar;
}// end of attemptMove
locationX += v.deltaX;
locationY += v.deltaY;
}// end for loop
startPoint = new ImPoint(locationX, locationY);
isBuildTrackSuccessful = okSoFar;
if (okSoFar) {
setCursorMessage("");
}
}
show();
}
}
private TrackMoveProducer.BuildMode getBuildMode() {
TrackMoveProducer.BuildMode mode;
mode = (TrackMoveProducer.BuildMode) modelRoot
.getProperty(ModelRoot.Property.TRACK_BUILDER_MODE);
return mode;
}
/**
* Saves track into real world
*/
public ImPoint updateWorld(TrackMoveProducer trackBuilder) {
ImPoint actPoint = getCursorPosition();
if (buildNewTrack) {
if (builtTrack.size() > 0) {
MoveStatus ms = moveCursorMoreTiles(builtTrack, trackBuilder);
/* Note, reset() will have been called if ms.ok == false */
if (ms.ok) {
actPoint = builtTrack.get(builtTrack.size() - 1);
builtTrack = new ArrayList<ImPoint>();
}
}
} else {
trackBuilder.setBuildTrackStrategy(getBts());
MoveStatus ms = trackBuilder.buildTrack(actPoint, path);
//MoveStatus ms = trackBuilder.buildTrack(startPoint, path);
if (ms.ok) {
actPoint = targetPoint;
setCursorMessage("");
if (REMOVE_TRACK == getBuildMode()) {
soundManager.playSound(
"/jfreerails/client/sounds/removetrack.wav", 0);
} else {
soundManager.playSound(
"/jfreerails/client/sounds/buildtrack.wav", 0);
}
} else {
setCursorMessage(ms.message);
reset();
}
}
hide();
return actPoint;
}
}

TrackPieceRendererList

Full name: jfreerails.client.renderer.TrackPieceRendererList

Documentation

/**
* A list of TrackPieceRenderers.
*
* @author Luke
*/

Source Code

/**
* A list of TrackPieceRenderers.
*
* @author Luke
*/
final public class TrackPieceRendererList {
private static final Logger logger = Logger
.getLogger(TrackPieceRendererList.class.getName());
private final TrackPieceRenderer[] trackPieceViewArray;
public TrackPieceRenderer getTrackPieceView(int i) {
if (NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER == i) {
return NullTrackPieceRenderer.instance;
}
return trackPieceViewArray[i];
}
public TrackPieceRendererList(ReadOnlyWorld w, ImageManager imageManager,
FreerailsProgressMonitor pm) throws IOException {
// Setup progress monitor..
pm.nextStep(w.size(SKEY.TRACK_RULES));
int progress = 0;
pm.setValue(progress);
int numberOfTrackTypes = w.size(SKEY.TRACK_RULES);
trackPieceViewArray = new TrackPieceRenderer[numberOfTrackTypes];
for (int i = 0; i < numberOfTrackTypes; i++) {
trackPieceViewArray[i] = new TrackPieceRendererImpl(w,
imageManager, i);
pm.setValue(++progress);
}
}
public boolean validate(ReadOnlyWorld w) {
boolean okSoFar = true;
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
Iterator<TrackConfiguration> legalConfigurationsIterator = trackRule
.getLegalConfigurationsIterator();
TrackPieceRenderer trackPieceView = this.getTrackPieceView(i);
if (null == trackPieceView) {
logger
.warning("No track piece view for the following track type: "
+ trackRule.getTypeName());
return false;
}
while (legalConfigurationsIterator.hasNext()) {
TrackConfiguration trackConfig = legalConfigurationsIterator
.next();
int trackGraphicsNo = trackConfig.getTrackGraphicsID();
Image img = trackPieceView.getTrackPieceIcon(trackGraphicsNo);
if (null == img) {
logger
.warning("No track piece image for the following track type: "
+ trackRule.getTypeName()
+ ", with configuration: "
+ trackGraphicsNo);
okSoFar = false;
}
}
}
return okSoFar;
}
}

ZoomedOutMapRenderer

Full name: jfreerails.client.renderer.ZoomedOutMapRenderer

Documentation

/**
* This class draws the overview map.
*
* @author Luke Lindsay
* @author Robert Tuck
*/

Source Code

/**
* This class draws the overview map.
*
* @author Luke Lindsay
* @author Robert Tuck
*/
final public class ZoomedOutMapRenderer implements MapRenderer {
private final int imageWidth;
private final int imageHeight;
private final int mapWidth;
private final int mapHeight;
private final int mapX;
private final int mapY;
private final ReadOnlyWorld w;
private BufferedImage one2oneImage;
private BufferedImage mapImage;
private final AffineTransform affineTransform;
// private Graphics2D mapGraphics;
private final GraphicsConfiguration defaultConfiguration = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
private boolean isDirty = true;
public static ZoomedOutMapRenderer getInstance(ReadOnlyWorld world,
Dimension maxSize) {
// Work with doubles to avoid rounding errors.
double worldWidth = world.getMapWidth();
double worldHeight = world.getMapHeight();
double scale;
if (worldWidth / worldHeight > maxSize.getWidth() / maxSize.getHeight()) {
scale = maxSize.getWidth() / worldWidth;
} else {
scale = maxSize.getHeight() / worldHeight;
}
double height = scale * worldHeight;
double width = scale * worldWidth;
return new ZoomedOutMapRenderer(world, (int) width, (int) height, 0, 0,
world.getMapWidth(), world.getMapHeight());
}
private ZoomedOutMapRenderer(ReadOnlyWorld world, int width, int height,
int mapX, int mapY, int mapWidth, int mapHeight) {
w = world;
this.mapWidth = mapWidth;
this.mapHeight = mapHeight;
imageHeight = height;
imageWidth = width;
double scalingFactor = ((double) imageHeight) / mapHeight;
affineTransform = AffineTransform.getScaleInstance(scalingFactor,
scalingFactor);
this.mapX = mapX;
this.mapY = mapY;
refresh();
}
public float getScale() {
return (float) imageHeight / (float) mapHeight;
}
public void paintRect(Graphics g, Rectangle visibleRect) {
renderOffScreenImage();
g.drawImage(mapImage, 0, 0, null);
}
private void renderOffScreenImage() {
if (isDirty) {
Graphics2D mapGraphics = mapImage.createGraphics();
mapGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
mapGraphics.setClip(0, 0, imageWidth, imageHeight);
mapGraphics.clearRect(0, 0, imageWidth, imageHeight);
mapGraphics.drawImage(one2oneImage, affineTransform, null);
isDirty = false;
}
}
private void refreshTile(Point tile) {
FreerailsTile tt = (FreerailsTile) w.getTile(tile.x, tile.y);
if (tt.getTrackPiece().equals(NullTrackPiece.getInstance())) {
int typeNumber = tt.getTerrainTypeID();
TerrainType terrainType = (TerrainType) w.get(SKEY.TERRAIN_TYPES,
typeNumber);
one2oneImage.setRGB(tile.x, tile.y, terrainType.getRGB());
} else {
/* black with alpha of 1 */
one2oneImage.setRGB(tile.x, tile.y, 0xff000000);
}
isDirty = true;
// int scaledX = (tile.x - mapX) * imageWidth / mapWidth;
// int scaledY = (tile.y - mapY) * imageHeight / mapHeight;
// int minx = scaledX < 2 ? 0 : scaledX - 2;
// int miny = scaledY < 2 ? 0 : scaledY - 2;
// int maxx = scaledX > imageWidth - 4 ? imageWidth : scaledX + 4;
// int maxy = scaledY > imageHeight - 4 ? imageHeight : scaledY + 4;
// mapGraphics.setClip(minx, miny, maxx - minx, maxy - miny);
// mapGraphics.clearRect(minx, miny, maxx - minx, maxy - miny);
// mapGraphics.drawImage(one2oneImage, affineTransform, null);
}
/**
* Redraw the whole map onto a new buffer.
*/
private void refresh() {
isDirty = true;
/* free up memory used by the old image */
if (mapImage != null) {
mapImage.flush();
}
if (one2oneImage != null) {
one2oneImage.flush();
}
// if (mapGraphics != null) {
// mapGraphics.dispose();
// }
/* generate a 1:1 map of the terrain layer */
one2oneImage = defaultConfiguration.createCompatibleImage(mapWidth,
mapHeight, Transparency.TRANSLUCENT);
mapImage = defaultConfiguration.createCompatibleImage(imageWidth,
imageHeight, Transparency.OPAQUE);
Point tile = new Point();
for (tile.x = mapX; tile.x < mapWidth + mapX; tile.x++) {
for (tile.y = mapY; tile.y < mapHeight + mapY; tile.y++) {
FreerailsTile tt = (FreerailsTile) w.getTile(tile.x, tile.y);
if (tt.getTrackPiece().equals(NullTrackPiece.getInstance())) {
int typeNumber = tt.getTerrainTypeID();
TerrainType terrainType = (TerrainType) w.get(
SKEY.TERRAIN_TYPES, typeNumber);
one2oneImage.setRGB(tile.x - mapX, tile.y - mapY,
terrainType.getRGB());
} else {
/* black with alpha of 1 */
one2oneImage.setRGB(tile.x - mapX, tile.y - mapY,
0xff000000);
}
}
}
renderOffScreenImage();
}
/*
* @see NewMapView#getMapSizeInPixels()
*/
public Dimension getMapSizeInPixels() {
return new Dimension(imageWidth, imageHeight);
}
public void paintTile(Graphics g, int tileX, int tileY) {
g.drawImage(mapImage, 0, 0, null);
}
public void refreshTile(int x, int y) {
refreshTile(new Point(x, y));
}
public void refreshAll() {
refresh();
}
}

BufferedTiledBackgroundRenderer

Full name: jfreerails.client.renderer.BufferedTiledBackgroundRenderer

Documentation

/**
* This abstract class stores a buffer of the background of the current visible
* rectangle of the map. Code that is independent of how tiles are represented,
* e.g. whether they are square or isometric, should go here.
*
* @author Luke Lindsay 06 October 2001
* @version 1.0
*
*/

Source Code

/**
* This abstract class stores a buffer of the background of the current visible
* rectangle of the map. Code that is independent of how tiles are represented,
* e.g. whether they are square or isometric, should go here.
*
* @author Luke Lindsay 06 October 2001
* @version 1.0
*
*/
public abstract class BufferedTiledBackgroundRenderer implements
MapLayerRenderer {
/**
* This is used to create images that are compatible with the default
* graphics configuration. Such images can be drawn to the screen quickly
* since no conversion is needed.
*/
private final GraphicsConfiguration defaultConfig = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice()
.getDefaultConfiguration();
/**
* Used to draw on the backbuffer.
*/
Graphics bg;
/**
* Used to draw on the backbuffer. It is translated so that to its users, it
* appears they are drawing on the actual map, not a buffered region of the
* map.
*
* translatedBg equals bg.translate(-bufferRect.x , -bufferRect.y);
*/
private Graphics translatedBg;
/**
* The bounds and location of the map region that is stored in the offscreen
* Image backgroundBuffer.
*/
final Rectangle bufferRect = new Rectangle();
/**
* An offscreen image storing the background of a region of the map.
*/
VolatileImage backgroundBuffer;
/**
* Updates the backbuffer as necessary, then draws it on to the Graphics
* object passed.
*
* @param outputGraphics
* Once it has been updated, the backbuffer is drawn onto this
* Graphics object.
* @param newVisibleRectangle
* The region of the map that the backbuffer must be updated to
* display.
*/
public void paintRect(Graphics outputGraphics,
Rectangle newVisibleRectangle) {
do {
/*
* If this is the first call to the paint method or the component
* has just been resized, we need to create a new backgroundBuffer.
*/
if ((backgroundBuffer == null)
|| (newVisibleRectangle.height != bufferRect.height)
|| (newVisibleRectangle.width != bufferRect.width)) {
setbackgroundBuffer(newVisibleRectangle.width,
newVisibleRectangle.height);
}
// Test if image is lost and restore it.
int valCode = backgroundBuffer.validate(defaultConfig);
if (valCode == VolatileImage.IMAGE_INCOMPATIBLE) {
setbackgroundBuffer(newVisibleRectangle.width,
newVisibleRectangle.height);
} else if (valCode == VolatileImage.IMAGE_RESTORED) {
resetGraphics();
this.refreshBackground();
}
/*
* Has the VisibleRectangle moved since the last paint?
*/
if ((bufferRect.x != newVisibleRectangle.x)
|| (bufferRect.y != newVisibleRectangle.y)) {
int dx = bufferRect.x - newVisibleRectangle.x;
int dy = bufferRect.y - newVisibleRectangle.y;
scrollbackgroundBuffer(dx, dy);
bufferRect.setBounds(newVisibleRectangle);
}
if ((bufferRect.width != newVisibleRectangle.width)
&& (bufferRect.height != newVisibleRectangle.height)) {
paintBufferRectangle(newVisibleRectangle.x - bufferRect.x,
newVisibleRectangle.y - bufferRect.y,
newVisibleRectangle.width,
newVisibleRectangle.height);
}
outputGraphics.drawImage(backgroundBuffer,
newVisibleRectangle.x, newVisibleRectangle.y, null);
bufferRect.setBounds(newVisibleRectangle);
} while (backgroundBuffer.contentsLost());
}
private void refreshBackground() {
paintBufferRectangle(0, 0, bufferRect.width, bufferRect.height);
}
public void refreshAll() {
refreshBackground();
}
private void setbackgroundBuffer(int w, int h) {
// Releases VRAM used by backgroundBuffer.
if (backgroundBuffer != null) {
backgroundBuffer.flush();
}
// Create new backgroundBuffer.
backgroundBuffer = defaultConfig.createCompatibleVolatileImage(w, h);
bufferRect.height = backgroundBuffer.getHeight(null);
bufferRect.width = backgroundBuffer.getWidth(null);
resetGraphics();
bg.clearRect(0, 0, w, h);
refreshBackground();
}
/** When the VolatileImage is created or restored, we need to (re)create the
Graphics objects.
*/
private void resetGraphics() {
if (bg != null) {
bg.dispose();
}
bg = backgroundBuffer.getGraphics();
if (translatedBg != null) {
translatedBg.dispose();
}
translatedBg = bg.create();
translatedBg.translate(-bufferRect.x, -bufferRect.y);
}
protected abstract void paintBufferRectangle(int x, int y, int width,
int height);
private void scrollbackgroundBuffer(int dx, int dy) {
int copyWidth = bufferRect.width;
int copyHeight = bufferRect.height;
int copySourceX = 0;
int copySourceY = 0;
if (dx > 0) {
copyWidth -= dx;
} else {
copyWidth += dx;
copySourceX = -dx;
}
if (dy > 0) {
copyHeight -= dy;
} else {
copyHeight += dy;
copySourceY = -dy;
}
bg.copyArea(copySourceX, copySourceY, copyWidth, copyHeight, dx, dy);
bufferRect.x -= dx;
bufferRect.y -= dy;
// paint exposed areas
if (dx != 0) {
if (dx > 0) {
bg.setClip(0, 0, dx, bufferRect.height);
bg.clearRect(0, 0, dx, bufferRect.height);
paintBufferRectangle(0, 0, dx, bufferRect.height);
} else {
bg.setClip(bufferRect.width + dx, 0, -dx, bufferRect.height);
bg.clearRect(bufferRect.width + dx, 0, -dx, bufferRect.height);
paintBufferRectangle(bufferRect.width + dx, 0, -dx,
bufferRect.height);
}
}
if (dy != 0) {
if (dy > 0) {
bg.setClip(0, 0, bufferRect.width, dy);
bg.clearRect(0, 0, bufferRect.width, dy);
paintBufferRectangle(0, 0, bufferRect.width, dy);
} else {
bg.setClip(0, bufferRect.height + dy, bufferRect.width, -dy);
bg.clearRect(0, bufferRect.height + dy, bufferRect.width, -dy);
paintBufferRectangle(0, bufferRect.height + dy,
bufferRect.width, -dy);
}
}
bg.setClip(0, 0, bufferRect.width, bufferRect.height);
}
}

StationBoxRenderer

Full name: jfreerails.client.renderer.StationBoxRenderer

Documentation

/**
* Renders box showing the cargo waiting at a station.
*
* @author Luke
*/

Source Code

/**
* Renders box showing the cargo waiting at a station.
*
* @author Luke
*/
public class StationBoxRenderer implements Painter {
private static final int WAGON_IMAGE_HEIGHT = 10;
private static final int SPACING = 3;
private static final int MAX_WIDTH = 80;
private final ReadOnlyWorld w;
private final Color bgColor;
private final int wagonImageWidth;
private final ModelRoot modelRoot;
private final Image[] cargoImages;
private static final int MAX_HEIGHT = 5 * (WAGON_IMAGE_HEIGHT + SPACING);
public StationBoxRenderer(ReadOnlyWorld world, RenderersRoot vl,
ModelRoot modelRoot) {
this.w = world;
this.bgColor = new Color(0, 0, 200, 60);
this.modelRoot = modelRoot;
// How wide will the wagon images be if we scale them so their height is
// WAGON_IMAGE_HEIGHT?
Image wagonImage = vl.getWagonImages(0).getSideOnImage();
wagonImageWidth = wagonImage.getWidth(null) * WAGON_IMAGE_HEIGHT
/ wagonImage.getHeight(null);
int nrOfCargoTypes = w.size(SKEY.CARGO_TYPES);
cargoImages = new Image[nrOfCargoTypes];
for (int i = 0; i < nrOfCargoTypes; i++) {
String wagonFilename = vl.getWagonImages(i).sideOnFileName;
try {
wagonImage = vl.getScaledImage(wagonFilename,
WAGON_IMAGE_HEIGHT);
} catch (IOException e) {
throw new IllegalArgumentException(wagonFilename);
}
cargoImages[i] = wagonImage;
}
}
public void paint(Graphics2D g) {
Boolean showCargoWaiting = (Boolean) modelRoot
.getProperty(ModelRoot.Property.SHOW_CARGO_AT_STATIONS);
if (showCargoWaiting.booleanValue()) {
/* We only show the station boxes for the current player. */
FreerailsPrincipal principal = modelRoot.getPrincipal();
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
while (wi.next()) { // loop over non null stations
StationModel station = (StationModel) wi.getElement();
int positionX = (station.getStationX() * Constants.TILE_SIZE)
+ Constants.TILE_SIZE / 2;
int positionY = (station.getStationY() * Constants.TILE_SIZE)
+ Constants.TILE_SIZE * 2;
Rectangle r = new Rectangle(positionX, positionY, MAX_WIDTH,
MAX_HEIGHT);
g.setColor(bgColor);
g.fillRect(positionX, positionY, MAX_WIDTH, MAX_HEIGHT);
g.setColor(Color.WHITE);
g.setStroke(new BasicStroke(1f));
g.drawRect(positionX, positionY, MAX_WIDTH, MAX_HEIGHT);
ImmutableCargoBundle cb = (ImmutableCargoBundle) w.get(
principal, KEY.CARGO_BUNDLES, station
.getCargoBundleID());
int[][] carsLoads = calculateCarLoads(cb);
for (int category = 0; category < CargoType
.getNumberOfCategories(); category++) {
int alternateWidth = (MAX_WIDTH - 2 * SPACING)
/ (carsLoads[category].length + 1);
int xOffsetPerWagon = Math.min(wagonImageWidth,
alternateWidth);
for (int car = 0; car < carsLoads[category].length; car++) {
int x = positionX + (car * xOffsetPerWagon)
+ SPACING;
int y = positionY
+ (category * (WAGON_IMAGE_HEIGHT + SPACING));
int cargoType = carsLoads[category][car];
g.drawImage(cargoImages[cargoType], x, y, null);
}
}
}
}
}
/**
* The length of the returned array is the number of complete carloads of
* the specified cargo category in the specified bundle. The values in the
* array are the type of the cargo. E.g. if the bundle contained 2 carloads
* of cargo type 3 and 1 of type 7, {3, 3, 7} would be returned.
*/
private int[][] calculateCarLoads(ImmutableCargoBundle cb) {
int categories = CargoType.getNumberOfCategories();
int numCargoTypes = w.size(SKEY.CARGO_TYPES);
int[] numberOfCarLoads = new int[categories];
int[][] cars = new int[categories][numCargoTypes];
for (int i = 0; i < numCargoTypes; i++) {
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, i);
int carsOfThisCargo = cb.getAmount(i)
/ WagonType.UNITS_OF_CARGO_PER_WAGON;
numberOfCarLoads[ct.getCategory().getNumber()] += carsOfThisCargo;
cars[ct.getCategory().getNumber()][i] += carsOfThisCargo;
}
int[][] returnMatrix = new int[categories][];
for (int category = 0; category < categories; category++) {
int[] returnValue = new int[numberOfCarLoads[category]];
int arrayIndex = 0;
for (int cargoType = 0; cargoType < numCargoTypes; cargoType++) {
for (int j = 0; j < cars[category][cargoType]; j++) {
returnValue[arrayIndex] = cargoType;
arrayIndex++;
}
}
returnMatrix[category] = returnValue;
}
return returnMatrix;
}
}

SquareTileBackgroundRenderer

Full name: jfreerails.client.renderer.SquareTileBackgroundRenderer

Documentation

/**
* This class stores a buffer containing the terrain and track layers of current
* visible rectangle of the map. It is responsible of painting these layers and
* updating the buffer when the map scrolls or tiles are updated.
*
* @author Luke Lindsay 01 November 2001
* @version 1.0
*/

Source Code

/**
* This class stores a buffer containing the terrain and track layers of current
* visible rectangle of the map. It is responsible of painting these layers and
* updating the buffer when the map scrolls or tiles are updated.
*
* @author Luke Lindsay 01 November 2001
* @version 1.0
*/
final public class SquareTileBackgroundRenderer extends BufferedTiledBackgroundRenderer {
private final MapLayerRenderer mapView;
@Override
protected void paintBufferRectangle(int x, int y, int width, int height) {
// Fix for bug [ 1303162 ]
// If the buffer hasn't been set yet, don't try and refresh it!
if (null != super.backgroundBuffer) {
Graphics gg = bg.create();
gg.setClip(x, y, width, height);
gg.translate(-bufferRect.x, -bufferRect.y);
mapView.paintRect(gg, bufferRect);
}
}
public SquareTileBackgroundRenderer(MapLayerRenderer mv) {
if (null == mv) {
throw new NullPointerException();
}
this.mapView = mv;
}
public void paintTile(Graphics g, int tileX, int tileY) {
mapView.paintTile(g, tileX, tileY);
}
public void refreshTile(int x, int y) {
// The backgroundBuffer gets created on the first call to
// backgroundBuffer.paintRect(..)
// so we need a check here to avoid a null pointer exception.
if (null != super.backgroundBuffer) {
Graphics gg = bg.create();
gg.translate(-bufferRect.x, -bufferRect.y);
mapView.paintTile(gg, x, y);
}
}
}

BuildTrackRenderer

Full name: jfreerails.client.renderer.BuildTrackRenderer

Documentation

/**
* This class draws the track being build.
*
* @author MystiqueAgent
* @author Luke
*
*/

Source Code

/**
* This class draws the track being build.
*
* @author MystiqueAgent
* @author Luke
*
*/
public class BuildTrackRenderer implements Painter {
public static final int BIG_DOT_WIDTH = 12;
public static final int SMALL_DOT_WIDTH = 6;
private final ModelRoot modelRoot;
private final Dimension tileSize = new Dimension(30, 30);
private RenderersRoot rr;
public BuildTrackRenderer(RenderersRoot trackPieceViewList,
ModelRoot modelRoot) {
this.modelRoot = modelRoot;
this.rr = trackPieceViewList;
}
private WorldDiffs getWorldDiffs() {
if (modelRoot == null) {
return null;
}
return (WorldDiffs) modelRoot
.getProperty(ModelRoot.Property.PROPOSED_TRACK);
}
/**
* Paints the proposed track and dots to distinguish the proposed track from
* any existing track.
*/
public void paint(Graphics2D g) {
WorldDiffs worldDiffs = getWorldDiffs();
if (null != worldDiffs) {
for (Iterator<ImPoint> iter = worldDiffs.getMapDiffs(); iter
.hasNext();) {
ImPoint point = iter.next();
FreerailsTile fp = (FreerailsTile)worldDiffs.getTile(point.x,
point.y);
TrackPiece tp = fp.getTrackPiece();
int graphicsNumber = tp.getTrackGraphicID();
int ruleNumber = tp.getTrackTypeID();
jfreerails.client.renderer.TrackPieceRenderer trackPieceView = rr
.getTrackPieceView(ruleNumber);
trackPieceView.drawTrackPieceIcon(graphicsNumber, g, point.x,
point.y, tileSize);
}
ReadOnlyWorld realWorld = modelRoot.getWorld();
/*
* Draw small dots for each tile whose track has changed. The dots
* are white if track has been added or upgraded and red if it has
* been removed.
*/
for (Iterator<ImPoint> iter = worldDiffs.getMapDiffs(); iter
.hasNext();) {
ImPoint p = iter.next();
int x = p.x * tileSize.width
+ (tileSize.width - SMALL_DOT_WIDTH) / 2;
int y = p.y * tileSize.width
+ (tileSize.height - SMALL_DOT_WIDTH) / 2;
FreerailsTile before = (FreerailsTile) realWorld.getTile(p.x,
p.y);
FreerailsTile after = (FreerailsTile) worldDiffs.getTile(p.x,
p.y);
boolean trackRemoved = !after.getTrackPiece().getTrackConfiguration().contains(
before.getTrackPiece().getTrackConfiguration());
Color dotColor = trackRemoved ? Color.RED : Color.WHITE;
g.setColor(dotColor);
g.fillOval(x, y, SMALL_DOT_WIDTH, SMALL_DOT_WIDTH);
}
}
}
}

ForestStyleTileRenderer

Full name: jfreerails.client.renderer.ForestStyleTileRenderer

Documentation

/**
* Looks to see whether the tiles to the left and right of the same type when
* deciding which tile icon to use.
*
* @author Luke Lindsay
*/

Source Code

/**
* Looks to see whether the tiles to the left and right of the same type when
* deciding which tile icon to use.
*
* @author Luke Lindsay
*/
final public class ForestStyleTileRenderer extends
jfreerails.client.renderer.AbstractTileRenderer {
private static final int[] X_LOOK_AT = { -1, 1 };
private static final int[] Y_LOOK_AT = { 0, 0 };
public ForestStyleTileRenderer(ImageManager imageManager, int[] rgbValues,
TerrainType tileModel) throws IOException {
super(tileModel, rgbValues);
this.setTileIcons(new Image[4]);
for (int i = 0; i < this.getTileIcons().length; i++) {
String fileName = generateRelativeFileName(i);
this.getTileIcons()[i] = imageManager.getImage(fileName);
}
}
@Override
public int selectTileIcon(int x, int y, ReadOnlyWorld w) {
int iconNumber = 0;
for (int i = 0; i < 2; i++) {
iconNumber = iconNumber
| checkTile(x + X_LOOK_AT[i], y + Y_LOOK_AT[i], w);
iconNumber = iconNumber << 1;
}
iconNumber = iconNumber >> 1;
return iconNumber;
}
@Override
public void dumpImages(ImageManager imageManager) {
for (int i = 0; i < this.getTileIcons().length; i++) {
String fileName = generateRelativeFileName(i);
imageManager.setImage(fileName, this.getTileIcons()[i]);
}
}
@Override
protected String generateFileNameNumber(int i) {
return BinaryNumberFormatter.format(i, 2);
}
}

MapRenderer

Full name: jfreerails.client.renderer.MapRenderer

Documentation

/**
* Lets the GUI component that is displaying the map known the scale at which
* the map is being rendered.
*
* @author Luke
*/

Source Code

/**
* Lets the GUI component that is displaying the map known the scale at which
* the map is being rendered.
*
* @author Luke
*/
public interface MapRenderer extends MapLayerRenderer {
float getScale();
Dimension getMapSizeInPixels();
}

AbstractTileRenderer

Full name: jfreerails.client.renderer.AbstractTileRenderer

Documentation

/**
* This class encapsulates the visible properties of a tile.
*
* @author Luke Lindsay
*/

Source Code

/**
* This class encapsulates the visible properties of a tile.
*
* @author Luke Lindsay
*/
public abstract class AbstractTileRenderer implements TileRenderer {
private final int[] typeNumbers;
private Image[] tileIcons;
private final TerrainType tileModel;
AbstractTileRenderer(TerrainType t, int[] rgbValues) {
tileModel = t;
this.typeNumbers = rgbValues;
if (null == t) {
throw new NullPointerException();
}
if (null == rgbValues) {
throw new NullPointerException();
}
}
public void renderTile(java.awt.Graphics g, int screenX, int screenY,
int mapX, int mapY, ReadOnlyWorld w) {
Image icon = this.getIcon(mapX, mapY, w);
if (null != icon) {
g.drawImage(icon, screenX, screenY, null);
}
}
public Image getDefaultIcon() {
return getTileIcons()[0];
}
String getTerrainType() {
return tileModel.getTerrainTypeName();
}
/**
* Returns an icon for the tile at x,y, which may depend on the terrain
* types of of the surrounding tiles.
*/
Image getIcon(int x, int y, ReadOnlyWorld w) {
int tile = selectTileIcon(x, y, w);
if (getTileIcons()[tile] != null) {
return getTileIcons()[tile];
}
throw new NullPointerException("Error in TileView.getIcon: icon no. "
+ tile + "==null");
}
int selectTileIcon(int x, int y, ReadOnlyWorld w) {
return 0;
}
int checkTile(int x, int y, ReadOnlyWorld w) {
int match = 0;
if (((x < w.getMapWidth()) && (x >= 0)) && (y < w.getMapHeight())
&& (y >= 0)) {
for (int i = 0; i < typeNumbers.length; i++) {
TerrainTile tt = (TerrainTile) w.getTile(x, y);
if (tt.getTerrainTypeID() == typeNumbers[i]) {
match = 1;
// A match
}
}
} else {
match = 1; // A match
/*
* If the tile we are checking is off the map, let it be a match.
* This stops coast appearing where the ocean meets the map edge.
*/
}
return match;
}
abstract public void dumpImages(ImageManager imageManager);
String generateRelativeFileName(int i) {
return "terrain" + File.separator + this.getTerrainType() + "_"
+ generateFileNameNumber(i) + ".png";
}
protected abstract String generateFileNameNumber(int i);
void setTileIcons(Image[] tileIcons) {
this.tileIcons = tileIcons;
}
Image[] getTileIcons() {
return tileIcons;
}
}

CityNamesRenderer

Full name: jfreerails.client.renderer.CityNamesRenderer

Documentation

/**
* Paints the city names on the map.
*
* @author Scott
*/

Source Code

/**
* Paints the city names on the map.
*
* @author Scott
*/
public class CityNamesRenderer implements Painter {
private final ReadOnlyWorld w;
public CityNamesRenderer(ReadOnlyWorld world) {
this.w = world;
}
public void paint(Graphics2D g) {
g.setColor(Color.WHITE);
g.setFont(new Font("Arial", 0, 20));
// draw city names onto map
for (int i = 0; i < w.size(SKEY.CITIES); i++) {
CityModel tempCity = (CityModel) w.get(SKEY.CITIES, i);
g.drawString(tempCity.getCityName(), tempCity.getCityX() * 30,
tempCity.getCityY() * 30 + 10);
}
}
}

NullTrackPieceRenderer

Full name: jfreerails.client.renderer.NullTrackPieceRenderer

Documentation

/**
* This class implements the TrackPieceView interface, but intentionally does
* nothing. Its methods are called when drawing tiles with no track.
*
* @author Luke
*/

Source Code

/**
* This class implements the TrackPieceView interface, but intentionally does
* nothing. Its methods are called when drawing tiles with no track.
*
* @author Luke
*/
final public class NullTrackPieceRenderer implements TrackPieceRenderer {
public static final NullTrackPieceRenderer instance = new NullTrackPieceRenderer();
private NullTrackPieceRenderer() {
}
/*
* @see TrackPieceView#getTrackPieceIcon(int)
*/
public Image getTrackPieceIcon(int trackTemplate) {
return null;
}
/*
* @see TrackPieceView#drawTrackPieceIcon(int, Graphics, int, int,
* Dimension)
*/
public void drawTrackPieceIcon(int trackTemplate, Graphics g, int x, int y,
Dimension tileSize) {
// Draw nothing since there no track here.
}
public void dumpImages(ImageManager imageManager) {
// TODO Auto-generated method stub
}
}

TileRenderer

Full name: jfreerails.client.renderer.TileRenderer

Documentation

/**
* Draws an icon to represent a tile.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* Draws an icon to represent a tile.
*
* @author Luke Lindsay
*
*/
public interface TileRenderer {
Image getDefaultIcon();
void renderTile(java.awt.Graphics g, int renderX, int renderY, int mapX,
int mapY, ReadOnlyWorld w);
/** Adds the images this TileRenderer uses to the specified ImageManager. */
void dumpImages(ImageManager imageManager);
}

RiverStyleTileRenderer

Full name: jfreerails.client.renderer.RiverStyleTileRenderer

Documentation

/**
* Selects a tile icon to use based on the type of the tiles to the North, East,
* South and West.
*
* @author Luke Lindsay
*/

Source Code

/**
* Selects a tile icon to use based on the type of the tiles to the North, East,
* South and West.
*
* @author Luke Lindsay
*/
final public class RiverStyleTileRenderer extends
jfreerails.client.renderer.AbstractTileRenderer {
private static final int[] Y_LOOK_AT = { 0, 1, 0, -1 };
private static final int[] X_LOOK_AT = { -1, 0, 1, 0 };
public RiverStyleTileRenderer(ImageManager imageManager, int[] rgbValues,
TerrainType tileModel) throws IOException {
super(tileModel, rgbValues);
this.setTileIcons(new Image[16]);
for (int i = 0; i < this.getTileIcons().length; i++) {
String fileName = generateRelativeFileName(i);
this.getTileIcons()[i] = imageManager.getImage(fileName);
}
}
@Override
public int selectTileIcon(int x, int y, ReadOnlyWorld w) {
int iconNumber = 0;
for (int i = 0; i < 4; i++) {
iconNumber = iconNumber << 1;
iconNumber = iconNumber
| checkTile(x + X_LOOK_AT[i], y + Y_LOOK_AT[i], w);
}
return iconNumber;
}
@Override
public void dumpImages(ImageManager imageManager) {
for (int i = 0; i < this.getTileIcons().length; i++) {
imageManager.setImage(generateRelativeFileName(i), this
.getTileIcons()[i]);
}
}
@Override
protected String generateFileNameNumber(int i) {
return BinaryNumberFormatter.formatWithLowBitOnLeft(i, 4);
}
}

StationNamesRenderer

Full name: jfreerails.client.renderer.StationNamesRenderer

Documentation

/**
*
* Class to render the station names and spheres of influence on the game map.
* Names are retrieved from the KEY.STATIONS object. Date: 14th April 2003 28
* May 2004 updated to also show station sphere of influence.
*
* @author Scott Bennett
* @author Luke Lindsay
*
*/

Source Code

/**
*
* Class to render the station names and spheres of influence on the game map.
* Names are retrieved from the KEY.STATIONS object. Date: 14th April 2003 28
* May 2004 updated to also show station sphere of influence.
*
* @author Scott Bennett
* @author Luke Lindsay
*
*/
public class StationNamesRenderer implements Painter {
private final ReadOnlyWorld w;
private final ModelRoot modelRoot;
private final int fontSize;
private final Color bgColor;
private final Color textColor;
final static float[] dash1 = { 5.0f };
final static BasicStroke dashed = new BasicStroke(1.0f,
BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f);
private final Font font;
public StationNamesRenderer(ReadOnlyWorld world, ModelRoot modelRoot) {
this.w = world;
this.modelRoot = modelRoot;
this.fontSize = 10;
this.bgColor = Color.BLACK;
this.textColor = Color.WHITE;
font = new Font("Arial", 0, fontSize);
}
public void paint(Graphics2D g) {
int rectWidth;
int rectHeight;
int rectX;
int rectY;
float visibleAdvance;
float textX;
float textY;
StationModel tempStation;
String stationName;
int positionX;
int positionY;
Boolean showStationNames = (Boolean) modelRoot
.getProperty(ModelRoot.Property.SHOW_STATION_NAMES);
Boolean showStationBorders = (Boolean) modelRoot
.getProperty(ModelRoot.Property.SHOW_STATION_BORDERS);
FontRenderContext frc = g.getFontRenderContext();
TextLayout layout;
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
// draw station names onto map
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
while (wi.next()) { // loop over non null stations
tempStation = (StationModel) wi.getElement();
int x = tempStation.getStationX();
int y = tempStation.getStationY();
// First draw station sphere of influence
if (showStationBorders.booleanValue()) {
FreerailsTile tile = (FreerailsTile) w.getTile(x, y);
int radius = tile.getTrackPiece().getTrackRule().getStationRadius();
int diameterInPixels = (radius * 2 + 1) * 30;
int radiusX = (x - radius) * 30;
int radiusY = (y - radius) * 30;
g.setColor(Color.WHITE);
g.setStroke(dashed);
g.draw(new RoundRectangle2D.Double(radiusX, radiusY,
diameterInPixels, diameterInPixels, 10, 10));
}
// Then draw the station name.
if (showStationNames.booleanValue()) {
stationName = tempStation.getStationName();
positionX = (x * 30) + 15;
positionY = (y * 30) + 30;
layout = new TextLayout(stationName, font, frc);
visibleAdvance = layout.getVisibleAdvance();
rectWidth = (int) (visibleAdvance * 1.2);
rectHeight = (int) (fontSize * 1.5);
rectX = (positionX - (rectWidth / 2));
rectY = positionY;
g.setColor(bgColor);
g.fillRect(rectX, rectY, rectWidth, rectHeight);
textX = (positionX - (visibleAdvance / 2));
textY = positionY + fontSize + 1;
g.setColor(textColor);
layout.draw(g, textX, textY);
g.setStroke(new BasicStroke(1.0f));
// draw a border 1 pixel inside the edges of the rectangle
g.draw(new Rectangle(rectX + 1, rectY + 1, rectWidth - 3,
rectHeight - 3));
}
}
}
// end FOR loop
}
// paint method
}

TrainRenderer

Full name: jfreerails.client.renderer.TrainRenderer

Documentation

/**
* This class draws a train from an overhead view.
*
* Also has a method that determines if a mouse click was on a train.
*
* @author Luke Lindsay 13-Oct-2002
*
*/

Source Code

/**
* This class draws a train from an overhead view.
*
* Also has a method that determines if a mouse click was on a train.
*
* @author Luke Lindsay 13-Oct-2002
*
*/
public class TrainRenderer {
private final RenderersRoot rr;
public TrainRenderer(RenderersRoot trainImages) {
this.rr = trainImages;
}
/**
* Calculates the positions of the engine and each wagon on the map.
* Intended to be used for rendering trains, for rendering highlights
* around trains, and for determining if a mouse click was on a train.
*
* @param train
* @param s
* @return List of positions, one entry for the engine and one for each
* wagon.
*/
public List<Entry<Point, Step>> calcPositions(TrainModel train, TrainPositionOnMap s) {
List<Entry<Point, Step>> positions = new ArrayList<>(train.getLength() + 1);
FreerailsPathIterator it = s.path();
PathWalker pw = new PathWalkerImpl(it);
// Engine + wagons
for (int i = 0; i < train.getNumberOfWagons() + 1; i++) {
IntLine wagon = new IntLine();
IntLine line = new IntLine();
pw.stepForward(16);
boolean firstIteration = true;
while (pw.hasNext()) {
pw.nextSegment(line);
if (firstIteration) {
wagon.x1 = line.x1;
wagon.y1 = line.y1;
firstIteration = false;
}
}
wagon.x2 = line.x2;
wagon.y2 = line.y2;
Step v = Step
.getNearestVector(wagon.x2 - wagon.x1, wagon.y2 - wagon.y1);
Point wagonCenter = new Point((wagon.x2 + wagon.x1) / 2,
(wagon.y2 + wagon.y1) / 2);
positions.add(new AbstractMap.SimpleImmutableEntry<>(wagonCenter, v));
// The gap between wagons
pw.stepForward(8);
while (pw.hasNext()) {
pw.nextSegment(line);
}
}
return positions;
}
public void paintTrain(Graphics g, TrainModel train, List<Entry<Point, Step>> positions) {
for (int i = 0; i < positions.size(); i++) {
TrainImages trainImages;
if (i == 0) {
trainImages = rr.getEngineImages(train.getEngineType());
} else {
int type = train.getWagon(i - 1);
trainImages = rr.getWagonImages(type);
}
Entry<Point, Step> entry = positions.get(i);
Image image = trainImages.getOverheadImage(entry.getValue().getID());
Point p = entry.getKey();
g.drawImage(image, p.x - 15, p.y - 15, null);
}
}
public void paintTrainHighlight(Graphics g, TrainModel train, List<Entry<Point, Step>> positions, TrainImages.Highlight highlight) {
for (int i = 0; i < positions.size(); i++) {
TrainImages trainImages;
if (i == 0) {
trainImages = rr.getEngineImages(train.getEngineType());
} else {
int type = train.getWagon(i - 1);
trainImages = rr.getWagonImages(type);
}
Entry<Point, Step> entry = positions.get(i);
Image image = trainImages.getOverheadHighlightImage(entry.getValue().getID(), highlight);
Point p = entry.getKey();
g.drawImage(image, p.x - 15, p.y - 15, null);
}
}
public boolean isHit(Point mousePosition, TrainModel train, List<Entry<Point, Step>> positions) {
for (int i = 0; i < positions.size(); i++) {
Entry<Point, Step> entry = positions.get(i);
Point p = entry.getKey();
int xDist = mousePosition.x - p.x;
int yDist = mousePosition.y - p.y;
int sumSquares = xDist * xDist + yDist * yDist;
if( sumSquares > 15 * 15){
continue;
}
TrainImages trainImages;
if (i == 0) {
trainImages = rr.getEngineImages(train.getEngineType());
} else {
int type = train.getWagon(i - 1);
trainImages = rr.getWagonImages(type);
}
BufferedImage image = (BufferedImage) trainImages.getOverheadImage(entry.getValue().getID());
int x = xDist + 15;
int y = yDist + 15;
Color c = new Color(image.getRGB(x, y), true);
int alpha = c.getAlpha();
if(alpha > 128){
return true;
}
}
return false;
}
public void paintTrain(Graphics g, TrainModel train, TrainPositionOnMap s, TrainImages.Highlight highlight) {
// If the train has been removed, it will be null!
if (train == null) {
return;
}
/*
* XXX HACK !! really our position ought to be defined at all times, but
* this is a workaround until we can fix movement
*/
if (s == null) {
return;
}
List<Entry<Point, Step>> positions = calcPositions(train, s);
if(null != highlight){
paintTrainHighlight(g, train, positions, highlight);
}
paintTrain(g, train, positions);
}
// @SonnyZ
// This code renders the explosion that occurs when 2 trains crash on the
// map
public void paintTrainCrash(Graphics g, TrainPositionOnMap s) {
// check to see if there is a train
// if (s == null) {
// return;
// }
// // Get the image for that frame of the explosion
// Image explosionImage = rr
// .getExplosionImage(s.getFrameCt() - 1);
// // draw the image
// for (int i = 0; i < s.getLength() - 1; i++) {
// Point wagonCenter = new Point(s.getX(i), s.getY(i));
// g.drawImage(explosionImage, wagonCenter.x - 15, wagonCenter.y - 15, null);
//
// }
// // increment the frame count
// s.incrementFramCt();
}
}

ChequeredTileRenderer

Full name: jfreerails.client.renderer.ChequeredTileRenderer

Documentation

/**
* Paints 2 variations of a tile icon a chequered pattern.
*
* @author Luke Lindsay
*/

Source Code

/**
* Paints 2 variations of a tile icon a chequered pattern.
*
* @author Luke Lindsay
*/
final public class ChequeredTileRenderer extends AbstractTileRenderer {
@Override
public int selectTileIcon(int x, int y, ReadOnlyWorld w) {
return (x + y) % 2;
}
public ChequeredTileRenderer(ImageManager imageManager, int[] rgbValues,
TerrainType tileModel) throws IOException {
super(tileModel, rgbValues);
this.setTileIcons(new Image[2]);
this.getTileIcons()[0] = imageManager
.getImage(generateRelativeFileName(0));
this.getTileIcons()[1] = imageManager
.getImage(generateRelativeFileName(1));
}
@Override
public void dumpImages(ImageManager imageManager) {
for (int i = 0; i < this.getTileIcons().length; i++) {
String fileName = generateRelativeFileName(i);
imageManager.setImage(fileName, this.getTileIcons()[i]);
}
}
@Override
protected String generateFileNameNumber(int i) {
return String.valueOf(i);
}
}

TrackPieceRendererImpl

Full name: jfreerails.client.renderer.TrackPieceRendererImpl

Documentation

/**
* This class renders a track piece.
*
* @author Luke Lindsay 09 October 2001
*/

Source Code

/**
* This class renders a track piece.
*
* @author Luke Lindsay 09 October 2001
*/
final public class TrackPieceRendererImpl implements TrackPieceRenderer {
private final Image[] trackPieceIcons = new Image[512];
private final String typeName;
public void drawTrackPieceIcon(int trackTemplate, java.awt.Graphics g,
int x, int y, java.awt.Dimension tileSize) {
if ((trackTemplate > 511) || (trackTemplate < 0)) {
throw new java.lang.IllegalArgumentException("trackTemplate = "
+ trackTemplate + ", it should be in the range 0-511");
}
if (trackPieceIcons[trackTemplate] != null) {
int drawX = x * tileSize.width - tileSize.width / 2;
int drawY = y * tileSize.height - tileSize.height / 2;
g.drawImage(trackPieceIcons[trackTemplate], drawX, drawY, null);
}
}
public TrackPieceRendererImpl(ReadOnlyWorld w, ImageManager imageManager,
int typeNumber) throws IOException {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, typeNumber);
this.typeName = trackRule.getTypeName();
for (int i = 0; i < 512; i++) {
if (trackRule.testTrackPieceLegality(i)) {
String fileName = generateFilename(i, getTrackTypeName());
trackPieceIcons[i] = imageManager.getImage(fileName);
}
}
}
public Image getTrackPieceIcon(int trackTemplate) {
if ((trackTemplate > 511) || (trackTemplate < 0)) {
throw new java.lang.IllegalArgumentException("trackTemplate = "
+ trackTemplate + ", it should be in the range 0-511");
}
return trackPieceIcons[trackTemplate];
}
public void dumpImages(ImageManager imageManager) {
for (int i = 0; i < 512; i++) {
if (trackPieceIcons[i] != null) {
String fileName = generateFilename(i, getTrackTypeName());
imageManager.setImage(fileName, trackPieceIcons[i]);
}
}
}
public static String generateFilename(int i, String trackTypeName) {
String relativeFileNameBase = "track" + File.separator + trackTypeName;
int newTemplate = TrackConfiguration.from9bitTemplate(i)
.get8bitTemplate();
String fileName = relativeFileNameBase + "_"
+ BinaryNumberFormatter.formatWithLowBitOnLeft(newTemplate, 8)
+ ".png";
return fileName;
}
private String getTrackTypeName() {
return typeName;
}
}

TileRendererListImpl

Full name: jfreerails.client.renderer.TileRendererListImpl

Documentation

/**
* A list of TileRenderers stored in an array and created from an ArrayList.
*
* @author Luke Lindsay 09 October 2001
*/

Source Code

/**
* A list of TileRenderers stored in an array and created from an ArrayList.
*
* @author Luke Lindsay 09 October 2001
*/
final public class TileRendererListImpl implements TileRendererList {
private final TileRenderer[] tiles;
public TileRenderer getTileViewWithNumber(int i) {
return tiles[i];
}
public TileRendererListImpl(ArrayList<TileRenderer> t) {
tiles = new TileRenderer[t.size()];
for (int i = 0; i < t.size(); i++) {
tiles[i] = t.get(i);
}
}
public boolean validate(ReadOnlyWorld w) {
// There should a TileRenderer for each terrain type.
return w.size(SKEY.TERRAIN_TYPES) == tiles.length;
}
}

TrackPieceRenderer

Full name: jfreerails.client.renderer.TrackPieceRenderer

Documentation

/**
* Draws an icon to represent a track piece.
*
* @author Luke Lindsay 09 October 2001
*/

Source Code

/**
* Draws an icon to represent a track piece.
*
* @author Luke Lindsay 09 October 2001
*/
public interface TrackPieceRenderer {
Image getTrackPieceIcon(int trackTemplate);
void drawTrackPieceIcon(int trackTemplate, java.awt.Graphics g, int x,
int y, java.awt.Dimension tileSize);
/** Adds the images this TileRenderer uses to the specified ImageManager. */
void dumpImages(ImageManager imageManager);
}

MapBackgroundRender

Full name: jfreerails.client.renderer.MapBackgroundRender

Documentation

/**
* This class encapsulates the objects that make-up and paint the background of
* the map view. At present it is composed of two layers: the terrain layer and
* the track layer.
*
* @author Luke Lindsay 21 September 2001
* @version 1
*/

Source Code

/**
* This class encapsulates the objects that make-up and paint the background of
* the map view. At present it is composed of two layers: the terrain layer and
* the track layer.
*
* @author Luke Lindsay 21 September 2001
* @version 1
*/
final public class MapBackgroundRender implements MapLayerRenderer {
private static final Logger logger = Logger
.getLogger(MapBackgroundRender.class.getName());
/**
* The terrain layer.
*/
private final TerrainLayer terrainLayer;
/**
* The track layer.
*/
private final TrackLayer trackLayer;
private final Dimension tileSize = new Dimension(30, 30);
private final Dimension mapSize;
private final Painter cityNames;
private final Painter stationNames;
/*
* Used to avoid having to create a new rectangle for each call to the paint
* methods.
*/
private Rectangle clipRectangle = new Rectangle();
/**
* This inner class represents a view of the track on the map.
*
* @author Luke Lindsay 21 September 2001
*/
final public class TrackLayer implements MapLayerRenderer {
private final ReadOnlyWorld w;
private final RenderersRoot rr;
/**
* Paints a rectangle of tiles onto the supplied graphics context.
*
* @param g
* The graphics context on which the tiles get painted.
* @param tilesToPaint
* The rectangle, measured in tiles, to paint.
*/
public void paintRectangleOfTiles(Graphics g, Rectangle tilesToPaint) {
/*
* Track can overlap the adjacent terrain tiles by half a tile. This
* means that we need to paint the track from the tiles bordering
* the specified rectangle of tiles (tilesToPaint). To prevent
* unnecessary painting, we set the clip to expose only the rectangle
* of tilesToPaint.
*/
Graphics tempG = g;
Point tile = new Point();
for (tile.x = tilesToPaint.x - 1; tile.x < (tilesToPaint.x
+ tilesToPaint.width + 1); tile.x++) {
for (tile.y = tilesToPaint.y - 1; tile.y < (tilesToPaint.y
+ tilesToPaint.height + 1); tile.y++) {
if ((tile.x >= 0) && (tile.x < mapSize.width)
&& (tile.y >= 0) && (tile.y < mapSize.height)) {
FreerailsTile ft = (FreerailsTile)w.getTile(tile.x, tile.y);
TrackPiece tp = ft.getTrackPiece();
int graphicsNumber = tp.getTrackGraphicID();
int ruleNumber = tp.getTrackTypeID();
if (ruleNumber != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
TrackPieceRenderer trackPieceView = rr.getTrackPieceView(ruleNumber);
trackPieceView.drawTrackPieceIcon(graphicsNumber,
tempG, tile.x, tile.y, tileSize);
}
}
}
}
}
public void paintTile(Graphics g, int tileX, int tileY) {
/*
* Since track tiles overlap the adjacent terrain tiles, we create a
* temporary Graphics object that only lets us draw on the selected
* tile.
*/
paintRectangleOfTiles(g, new Rectangle(tileX, tileY, 1, 1));
}
private void paintRectangleOfTiles(Graphics g, int x, int y, int width,
int height) {
paintRectangleOfTiles(g, new Rectangle(x, y, width, height));
}
public void refreshTile(int x, int y) {
}
public void paintRect(Graphics g, Rectangle visibleRect) {
throw new UnsupportedOperationException(
"Method not yet implemented.");
}
public TrackLayer(ReadOnlyWorld world,
RenderersRoot trackPieceViewList) {
this.rr = trackPieceViewList;
this.w = world;
}
public void refreshAll() {
}
}
/**
* This inner class represents the terrain of the map.
*
* @author Luke Lindsay 21 September 2001
*/
final public class TerrainLayer implements MapLayerRenderer {
private final TileRendererList tiles;
private final ReadOnlyWorld w;
public void paintTile(Graphics g, Point tile) {
int screenX = tileSize.width * tile.x;
int screenY = tileSize.height * tile.y;
if ((tile.x >= 0) && (tile.x < mapSize.width) && (tile.y >= 0)
&& (tile.y < mapSize.height)) {
TerrainTile tt = (TerrainTile) w.getTile(tile.x, tile.y);
int typeNumber = tt.getTerrainTypeID();
TileRenderer tr = tiles.getTileViewWithNumber(typeNumber);
if (null == tr) {
logger.warning("No tile renderer for " + typeNumber);
} else {
tr.renderTile(g, screenX, screenY, tile.x, tile.y, w);
}
}
}
/**
* Paints a rectangle of tiles on the supplied graphics context.
*
* @param g
* The graphics context.
* @param tilesToPaint
* The rectangle, measured in tiles, to paint.
*/
public void paintRectangleOfTiles(Graphics g, Rectangle tilesToPaint) {
Point tile = new Point();
for (tile.x = tilesToPaint.x; tile.x < (tilesToPaint.x + tilesToPaint.width); tile.x++) {
for (tile.y = tilesToPaint.y; tile.y < (tilesToPaint.y + tilesToPaint.height); tile.y++) {
terrainLayer.paintTile(g, tile);
}
}
}
public void paintRect(Graphics g, Rectangle visibleRect) {
throw new UnsupportedOperationException(
"Method not yet implemented.");
}
public void paintTile(Graphics g, int tileX, int tileY) {
paintTile(g, new Point(tileX, tileY));
}
private void paintRectangleOfTiles(Graphics g, int x, int y, int width,
int height) {
paintRectangleOfTiles(g, new Rectangle(x, y, width, height));
}
public void refreshTile(int x, int y) {
}
public TerrainLayer(ReadOnlyWorld world, TileRendererList tiles) {
this.w = world;
this.tiles = tiles;
}
public void refreshAll() {
}
}
public MapBackgroundRender(ReadOnlyWorld w, RenderersRoot rr,
ModelRoot modelRoot) {
trackLayer = new TrackLayer(w, rr);
terrainLayer = new TerrainLayer(w, rr);
mapSize = new Dimension(w.getMapWidth(), w.getMapHeight());
cityNames = new CityNamesRenderer(w);
stationNames = new StationNamesRenderer(w, modelRoot);
}
public void paintTile(Graphics g, int x, int y) {
terrainLayer.paintTile(g, x, y);
trackLayer.paintTile(g, x, y);
cityNames.paint((Graphics2D) g);
stationNames.paint((Graphics2D) g);
}
public void paintRect(Graphics g, Rectangle visibleRect) {
int tileWidth = 30;
int tileHeight = 30;
clipRectangle = g.getClipBounds(clipRectangle);
int x = clipRectangle.x / tileWidth;
int y = clipRectangle.y / tileHeight;
int width = (clipRectangle.width / tileWidth) + 2;
int height = (clipRectangle.height) / tileHeight + 2;
paintRectangleOfTiles(g, x, y, width, height);
cityNames.paint((Graphics2D) g);
stationNames.paint((Graphics2D) g);
}
private void paintRectangleOfTiles(Graphics g, int x, int y, int width,
int height) {
terrainLayer.paintRectangleOfTiles(g, x, y, width, height);
trackLayer.paintRectangleOfTiles(g, x, y, width, height);
cityNames.paint((Graphics2D) g);
stationNames.paint((Graphics2D) g);
}
public void refreshTile(int x, int y) {
// Do nothing
}
public void refreshAll() {
// Do nothing
}
}

RenderersRoot

Full name: jfreerails.client.renderer.RenderersRoot

Documentation

/**
* Provides access to the objects that render terrain, track, and trains.
*
* @author Luke
*/

Source Code

/**
* Provides access to the objects that render terrain, track, and trains.
*
* @author Luke
*/
public interface RenderersRoot extends TileRendererList {
TrackPieceRenderer getTrackPieceView(int i);
TrainImages getWagonImages(int type);
TrainImages getEngineImages(int type);
//OldTrainImages getTrainImages();
boolean validate(ReadOnlyWorld world);
Image getImage(String relativeFilename) throws IOException;
Image getScaledImage(String relativeFilename, int height) throws IOException;
}

SpecialTileRenderer

Full name: jfreerails.client.renderer.SpecialTileRenderer

Documentation

/**
* A special tile's icon gets drawn over the icon of a normal tile.
*
* @author Luke Lindsay
*/

Source Code

/**
* A special tile's icon gets drawn over the icon of a normal tile.
*
* @author Luke Lindsay
*/
final public class SpecialTileRenderer extends AbstractTileRenderer {
private static final Logger logger = Logger
.getLogger(SpecialTileRenderer.class.getName());
final private TileRenderer parentTileView;
@Override
public void renderTile(java.awt.Graphics g, int renderX, int renderY,
int mapX, int mapY, ReadOnlyWorld w) {
if (parentTileView != null) {
parentTileView.renderTile(g, renderX, renderY, mapX, mapY, w);
} else {
logger.warning("parent tileView==null");
}
Image icon = this.getIcon(mapX, mapX, w);
if (null != icon) {
g.drawImage(icon, renderX, renderY, null);
} else {
logger.warning("special tileView icon==null");
}
}
@Override
public int selectTileIcon(int x, int y, ReadOnlyWorld w) {
return 0;
}
public SpecialTileRenderer(ImageManager imageManager, int[] rgbValues,
TerrainType tileModel, TileRenderer parentTileView)
throws IOException {
super(tileModel, rgbValues);
this.setTileIcons(new Image[1]);
this.getTileIcons()[0] = imageManager.getImage(generateFilename());
this.parentTileView = parentTileView;
}
@Override
public void dumpImages(ImageManager imageManager) {
imageManager.setImage(generateFilename(), this.getTileIcons()[0]);
}
private String generateFilename() {
return "terrain" + File.separator + this.getTerrainType() + ".png";
}
@Override
protected String generateFileNameNumber(int i) {
throw new UnsupportedOperationException();
}
}

TrainImages

Full name: jfreerails.client.renderer.TrainImages

Documentation

/**
* Stores side-on and over-head images of a particular wagon or engine type.
*
* @author Luke
*
*
*/

Source Code

/**
* Stores side-on and over-head images of a particular wagon or engine type.
*
* @author Luke
*
*
*/
public class TrainImages {
public enum Highlight{SELECTED, FOCUSED};
private final Image sideOnImage;
private final Image[] overheadImages = new Image[8];
private final Image[] overheadSelectedImages = new Image[8];
private final Image[] overheadFocusedImages = new Image[8];
public final String sideOnFileName;
public Image getSideOnImage() {
return sideOnImage;
}
public Image getOverheadImage(int direction) {
return overheadImages[direction];
}
/**
* @param direction
* @return the image to render under the wagon/engine image
* when the train is selects/focused.
*/
public Image getOverheadHighlightImage(int direction, Highlight h) {
if(h == Highlight.FOCUSED)
return overheadFocusedImages[direction];
if(h == Highlight.SELECTED)
return overheadSelectedImages[direction];
return null;
}
public static String generateOverheadFilename(String name, int i) {
Step[] vectors = Step.getList();
return "trains" + File.separator + "overhead" + File.separator + name
+ "_" + vectors[i].toAbrvString() + ".png";
}
public static String generateSideOnFilename(String name) {
return "trains" + File.separator + "sideon" + File.separator + name
+ ".png";
}
public TrainImages(ImageManager imageManager, String name) throws IOException {
sideOnFileName = TrainImages.generateSideOnFilename(name);
sideOnImage = imageManager.getImage(sideOnFileName);
for (int direction = 0; direction < 8; direction++) {
overheadImages[direction] = imageManager
.getImage(generateOverheadFilename(name, direction));
overheadSelectedImages[direction] = imageManager
.getImage(generateOverheadFilename("highlights" + File.separator + "selected", direction));
overheadFocusedImages[direction] = imageManager
.getImage(generateOverheadFilename("highlights" + File.separator + "focused", direction));
}
}
}

StandardTileRenderer

Full name: jfreerails.client.renderer.StandardTileRenderer

Documentation

/**
* Paints a tile for which there only one tile icon.
*
* @author Luke Lindsay
*/

Source Code

/**
* Paints a tile for which there only one tile icon.
*
* @author Luke Lindsay
*/
final public class StandardTileRenderer extends
jfreerails.client.renderer.AbstractTileRenderer {
public StandardTileRenderer(ImageManager imageManager, int[] rgbValues,
TerrainType tileModel) throws IOException {
super(tileModel, rgbValues);
this.setTileIcons(new Image[1]);
this.getTileIcons()[0] = imageManager.getImage(generateFilename());
}
@Override
public void dumpImages(ImageManager imageManager) {
imageManager.setImage(generateFilename(), this.getTileIcons()[0]);
}
private String generateFilename() {
return generateFilename(this.getTerrainType());
}
public static String generateFilename(String typeName) {
return "terrain" + File.separator + typeName + ".png";
}
@Override
protected String generateFileNameNumber(int i) {
throw new UnsupportedOperationException();
}
}

BlankMapRenderer

Full name: jfreerails.client.renderer.BlankMapRenderer

Documentation

/**
* Used for testing the Map view components without setting up any map data.
*
* @author Luke
*/

Source Code

/**
* Used for testing the Map view components without setting up any map data.
*
* @author Luke
*/
public class BlankMapRenderer implements MapRenderer {
private final float scale;
public BlankMapRenderer(float s) {
scale = s;
}
public float getScale() {
return scale;
}
public Dimension getMapSizeInPixels() {
int height = (int) (400 * scale);
int width = (int) (400 * scale);
return new Dimension(height, width);
}
public void paintTile(Graphics g, int tileX, int tileY) {
paintRect(g, null);
}
public void refreshTile(int x, int y) {
}
public void paintRect(Graphics g, Rectangle visibleRect) {
g.setColor(Color.darkGray);
g.fillRect(0, 0, (int) (scale * 400), (int) (scale * 400));
g.setColor(Color.blue);
int x = (int) (100 * scale);
int y = (int) (100 * scale);
int height = (int) (200 * scale);
int width = (int) (200 * scale);
g.fillRect(x, y, height, width);
}
public void refreshAll() {
// do nothing
}
}

StationRadiusRenderer

Full name: jfreerails.client.renderer.StationRadiusRenderer

Documentation

/**
* This class draws the radius of a station on the map.
*
* @author Luke
*/

Source Code

/**
* This class draws the radius of a station on the map.
*
* @author Luke
*/
public class StationRadiusRenderer implements Painter {
/**
* Border colour to use when placement is OK.
*/
public static final Color COLOR_OK = Color.WHITE;
/**
* Border colour to use when placement is not allowed.
*/
public static final Color COLOR_CANNOT_BUILD = Color.RED;
/**
* Colour of the highlighted border.
*/
private Color borderColor = COLOR_OK;
private static final int tileSize = 30;
private int radius = 2;
private int x;
private int y;
private final ModelRoot modelRoot;
public StationRadiusRenderer(ModelRoot mr) {
this.modelRoot = mr;
}
public void setBorderColor(Color c) {
borderColor = c;
}
public void setPosition(int x, int y) {
this.x = x;
this.y = y;
}
public void setRadius(int radius) {
this.radius = radius;
}
public void show() {
if (!modelRoot
.is(Property.CURSOR_MODE, Value.PLACE_STATION_CURSOR_MODE)) {
modelRoot.setProperty(Property.PREVIOUS_CURSOR_MODE, modelRoot
.getProperty(Property.CURSOR_MODE));
modelRoot.setProperty(Property.CURSOR_MODE,
Value.PLACE_STATION_CURSOR_MODE);
modelRoot.setProperty(Property.IGNORE_KEY_EVENTS, Boolean.TRUE);
}
}
public void hide() {
ModelRoot.Value lastCursorMode = (ModelRoot.Value) modelRoot
.getProperty(ModelRoot.Property.PREVIOUS_CURSOR_MODE);
assert !lastCursorMode
.equals(ModelRoot.Value.PLACE_STATION_CURSOR_MODE);
modelRoot.setProperty(ModelRoot.Property.CURSOR_MODE, lastCursorMode);
modelRoot.setProperty(Property.IGNORE_KEY_EVENTS, Boolean.FALSE);
}
public void paint(Graphics2D g) {
if (modelRoot.getProperty(ModelRoot.Property.CURSOR_MODE).equals(
Value.PLACE_STATION_CURSOR_MODE)) {
g.setStroke(new BasicStroke(2f));
g.setColor(borderColor);
g.drawRect(tileSize * (x - radius), tileSize * (y - radius),
tileSize * (2 * radius + 1), tileSize * (2 * radius + 1));
}
}
}

MapLayerRenderer

Full name: jfreerails.client.renderer.MapLayerRenderer

Documentation

/**
* Paints a layer of the map which might be buffered.
*
* @author Luke Lindsay
*/

Source Code

/**
* Paints a layer of the map which might be buffered.
*
* @author Luke Lindsay
*/
public interface MapLayerRenderer {
void paintTile(Graphics g, int tileX, int tileY);
void refreshTile(int x, int y);
void refreshAll();
void paintRect(Graphics g, Rectangle visibleRect);
}

CityTilePositioner

Full name: jfreerails.server.CityTilePositioner

Documentation

/**
* This class initialises cities and controls their growth. It makes changes to
* directly to the world object, so if the game has already started, use
* WorldDifferences and MapDiffMove to pass changes to the clients.
*
* @author Luke
*
*/

Source Code

/**
* This class initialises cities and controls their growth. It makes changes to
* directly to the world object, so if the game has already started, use
* WorldDifferences and MapDiffMove to pass changes to the clients.
*
* @author Luke
*
*/
public class CityTilePositioner {
Random random = new Random();
ArrayList<TerrainType> urbanTerrainTypes = new ArrayList<TerrainType>();
ArrayList<TerrainType> industryTerrainTypes = new ArrayList<TerrainType>();
ArrayList<TerrainType> resourceTerrainTypes = new ArrayList<TerrainType>();
World w;
public CityTilePositioner(World w) {
this.w = w;
// get the different types of Urban/Industry/Resource terrain
for (int i = 0; i < w.size(SKEY.TERRAIN_TYPES); i++) {
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
switch (type.getCategory().ordinal()) {
case 0:
urbanTerrainTypes.add(type);
break;
case 6:
industryTerrainTypes.add(type);
break;
case 7:
resourceTerrainTypes.add(type);
break;
}
}
}
void initCities() {
final int numCities = w.size(SKEY.CITIES);
CityEconomicModel[] cities = new CityEconomicModel[numCities];
for (int cityId = 0; cityId < numCities; cityId++) {
CityEconomicModel city = new CityEconomicModel();
city.loadFromMap(w, cityId);
final int urbanTiles = 2 + random.nextInt(3);
for (int i = 0; i < urbanTiles; i++) {
addUrbanTile(city);
}
final int industryTiles = random.nextInt(3);
for (int i = 0; i < industryTiles; i++) {
addIndustryTile(city);
}
final int resourceTiles = random.nextInt(3);
for (int i = 0; i < resourceTiles; i++) {
addResourceTile(city);
}
city.write2map(w);
cities[cityId] = city;
}
}
private void addResourceTile(CityEconomicModel city) {
int tileTypeNo = random.nextInt(resourceTerrainTypes.size());
TerrainType type = resourceTerrainTypes.get(tileTypeNo);
city.addTile(type);
}
private void addIndustryTile(CityEconomicModel city) {
int size = city.industriesNotAtCity.size();
if (size > 0) {
int tileTypeNo = random.nextInt(size);
TerrainType type = city.industriesNotAtCity.get(tileTypeNo);
city.addTile(type);
}
}
private void addUrbanTile(CityEconomicModel city) {
int tileTypeNo = random.nextInt(urbanTerrainTypes.size());
TerrainType type = urbanTerrainTypes.get(tileTypeNo);
city.addTile(type);
}
void growCities() {
final int numCities = w.size(SKEY.CITIES);
/*
* At some stage this will be refined to take into account how much
* cargo has been picked up and delivered and what city tiles are
* already present.
*/
for (int cityId = 0; cityId < numCities; cityId++) {
CityEconomicModel city = new CityEconomicModel();
city.loadFromMap(w, cityId);
// Only increase cities with stations and less than 16 tiles
if (city.size() < 16 && city.stations > 0) {
switch (random.nextInt(10)) {
case 0:
case 1:
addResourceTile(city); // 20% chance
break;
case 2:
case 3:
case 4:
case 5:
addUrbanTile(city); // 40% chance
break;
case 6:
addIndustryTile(city); // 10% chance
break;
default:
// do nothing, 30% chance
break;
}
city.write2map(w);
}
}
}
}

CitySAXParser

Full name: jfreerails.server.CitySAXParser

Documentation

/**
*
* Class to parse an xml file that contains city names and co-ords. Upon reading
* in the data, its stored in KEY.CITIES.
*
* @author Scott Bennett Date: 31st March 2003
*/

Source Code

/**
*
* Class to parse an xml file that contains city names and co-ords. Upon reading
* in the data, its stored in KEY.CITIES.
*
* @author Scott Bennett Date: 31st March 2003
*/
public class CitySAXParser extends DefaultHandler {
private final Vector<CityModel> cities;
private final World world;
public CitySAXParser(World w) throws SAXException {
world = w;
cities = new Vector<CityModel>();
}
@Override
public void endDocument() throws SAXException {
for (int i = 0; i < cities.size(); i++) {
CityModel tempCity = cities.elementAt(i);
world.add(SKEY.CITIES, new CityModel(tempCity.getCityName(),
tempCity.getCityX(), tempCity.getCityY()));
}
}
@Override
public void startElement(String namespaceURI, String sName, String qName,
Attributes attrs) throws SAXException {
String cityName = null;
int x = 0;
int y = 0;
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
String aName = attrs.getLocalName(i); // Attr name
if (aName.equals("")) {
aName = attrs.getQName(i);
}
// put values in CityModel obj
if (aName.equals("name")) {
cityName = attrs.getValue(i);
}
if (aName.equals("x")) {
x = Integer.parseInt(attrs.getValue(i));
}
if (aName.equals("y")) {
y = Integer.parseInt(attrs.getValue(i));
CityModel city = new CityModel(cityName, x, y);
cities.addElement(city);
}
}
// end for loop
}
// end if
}
// end startElement method
}

MapFixtureFactory2

Full name: jfreerails.server.MapFixtureFactory2

Documentation

/**
* Stores a static world object and provides copies to clients.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* Stores a static world object and provides copies to clients.
*
* @author Luke Lindsay
*
*/
public class MapFixtureFactory2 {
private static World w;
/**
* Returns a world object with a map of size 50*50, 4 players, and track,
* terrain and cargo types as specified in the xml files used by the actual
* game.
*/
synchronized public static World getCopy() {
if (null == w) {
w = generateWorld();
}
return w.defensiveCopy();
}
private static World generateWorld() {
World world = new WorldImpl(50, 50);
TileSetFactory tileFactory = new TileSetFactoryImpl();
WagonAndEngineTypesFactory wetf = new WagonAndEngineTypesFactory();
wetf.addTypesToWorld(world);
tileFactory.addTerrainTileTypesList(world);
URL track_xml_url = OldWorldImpl.class
.getResource("/jfreerails/data/track_tiles.xml");
Track_TilesHandlerImpl trackSetFactory = new Track_TilesHandlerImpl(
track_xml_url);
trackSetFactory.addTrackRules(world);
// Add 4 players
for (int i = 0; i < 4; i++) {
String name = "player" + i;
Player p = new Player(name, i);
AddPlayerMove move = AddPlayerMove.generateMove(world, p);
MoveStatus ms = move.doMove(world, Player.AUTHORITATIVE);
assert(ms.ok);
}
world.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
world.setTime(new GameTime(0));
world.set(ITEM.GAME_SPEED, new GameSpeed(10));
world.set(ITEM.GAME_RULES, GameRules.DEFAULT_RULES);
int clearTypeID = 0;
// Fill the world with clear terrain.
for (int i = 0; i < world.size(SKEY.TERRAIN_TYPES); i++) {
TerrainType tt = (TerrainType) world.get(SKEY.TERRAIN_TYPES, i);
if ("Clear".equals(tt.getTerrainTypeName())) {
clearTypeID = i;
break;
}
}
FreerailsTile tile = FreerailsTile.getInstance(clearTypeID);
for (int x = 0; x < world.getMapWidth(); x++) {
for (int y = 0; y < world.getMapHeight(); y++) {
world.setTile(x, y, tile);
}
}
return world;
}
}

ServerAutomaton

Full name: jfreerails.server.ServerAutomaton

Documentation

/**
* This interface is implemented by objects which are responsible for updating
* the game world. They are serialized when the game is saved. They are internal
* clients of the ServerGameEngine and need to be initialised with a connection
* to the game when deserialized.
*
* @author rob
*/

Source Code

/**
* This interface is implemented by objects which are responsible for updating
* the game world. They are serialized when the game is saved. They are internal
* clients of the ServerGameEngine and need to be initialised with a connection
* to the game when deserialized.
*
* @author rob
*/
public interface ServerAutomaton extends Serializable {
/**
* Initializes the automaton with a connection to the MoveExecutor.
*/
public void initAutomaton(MoveReceiver mr);
}

Methods

SavFileFilter

Full name: jfreerails.server.SavFileFilter

Documentation

/**
* A SavedGamesManager reads and writes gzipped saved games to the working
* directory.
*
* @author Luke
*
*/

Source Code

/**
* A SavedGamesManager reads and writes gzipped saved games to the working
* directory.
*
* @author Luke
*
*/
class SavFileFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return (name.endsWith(".sav"));
}
}

Methods

SavedGamesManagerImpl

Full name: jfreerails.server.SavedGamesManagerImpl

Documentation

/**
* Manages saved games, providing methods to retrieve game names, save game states, load game states, and create new maps.
*
* @see SavedGamesManager
* @see NewGameMessage2Server
* @see SavFileFilter
* @see ServerControl
* @see OldWorldImpl
* @see FreerailsProgressMonitor
*/

Source Code

public class SavedGamesManagerImpl implements SavedGamesManager {
private static final Logger logger = Logger
.getLogger(SavedGamesManagerImpl.class.getName());
public String[] getSaveGameNames() {
java.io.File dir = new File("./");
FilenameFilter filter = new SavFileFilter();
String[] files = dir.list(filter);
return files;
}
public String[] getNewMapNames() {
return NewGameMessage2Server.getMapNames();
}
public void saveGame(Serializable w, String s) throws IOException {
long startTime = System.currentTimeMillis();
logger.info("Saving game.. " + s);
FileOutputStream out = new FileOutputStream(s);
GZIPOutputStream zipout = new GZIPOutputStream(out);
ObjectOutputStream objectOut = new ObjectOutputStream(zipout);
objectOut.writeObject(ServerControlInterface.VERSION);
objectOut.writeObject(w);
objectOut.flush();
objectOut.close();
out.close();
long finishTime = System.currentTimeMillis();
long deltaTime = finishTime - startTime;
logger.info("done, " + deltaTime + "ms");
}
public Serializable loadGame(String name) throws IOException {
long startTime = System.currentTimeMillis();
logger.info("Loading game.. " + name);
FileInputStream in = new FileInputStream(name);
GZIPInputStream zipin = new GZIPInputStream(in);
ObjectInputStream objectIn = new ObjectInputStream(zipin);
String version_string;
try {
version_string = (String) objectIn.readObject();
if (!ServerControlInterface.VERSION.equals(version_string)) {
throw new IOException(version_string);
}
Serializable game = (Serializable) objectIn.readObject();
/**
* load player private data
*/
// for (int i = 0; i < world.getNumberOfPlayers(); i++) {
// Player player = world.getPlayer(i);
// player.loadSession(objectIn);
// }
long finishTime = System.currentTimeMillis();
long deltaTime = finishTime - startTime;
logger.info("done, " + deltaTime + "ms");
return game;
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IOException(e.getMessage());
} catch (InvalidClassException e) {
// e.printStackTrace();
throw new IOException(e.getMessage());
}
}
public Serializable newMap(String name) throws IOException {
return OldWorldImpl.createWorldFromMapFile(name,
FreerailsProgressMonitor.NULL_INSTANCE);
}
}

TrainPathFinder

Full name: jfreerails.server.TrainPathFinder

Documentation

/**
* This class provides methods that generate a path to a target as a series of
* PositionOnTrack objects encoded as ints, it also deals with stops at
* stations.
*
* @author Luke Lindsay 28-Nov-2002
*/

Source Code

/**
* This class provides methods that generate a path to a target as a series of
* PositionOnTrack objects encoded as ints, it also deals with stops at
* stations.
*
* @author Luke Lindsay 28-Nov-2002
*/
public class TrainPathFinder implements FreerailsIntIterator, ServerAutomaton {
private static final long serialVersionUID = 3256446893302559280L;
private final SimpleAStarPathFinder pathFinder = new SimpleAStarPathFinder();
private final FreerailsPrincipal principal;
private final TrainStopsHandler stopsHandler;
private final FlatTrackExplorer trackExplorer;
private final int trainId;
private transient MoveReceiver mr = null;
ReadOnlyWorld w;
public TrainPathFinder(FlatTrackExplorer tx, ReadOnlyWorld w,
int trainNumber, MoveReceiver newMr, FreerailsPrincipal p) {
this.trackExplorer = tx;
this.trainId = trainNumber;
principal = p;
stopsHandler = new TrainStopsHandler(trainId, principal, new WorldDiffs(w));
this.mr = newMr;
this.w = w;
}
public boolean hasNextInt() {
boolean moving = stopsHandler.isTrainMoving();
if (moving) {
return trackExplorer.hasNextEdge();
}
mr.processMove(stopsHandler.getMoves());
return false;
}
public void initAutomaton(MoveReceiver newMr) {
this.mr = newMr;
}
boolean isTrainMoving() {
boolean moving = stopsHandler.isTrainMoving();
mr.processMove(stopsHandler.getMoves());
return moving;
}
/**
* @return a PositionOnTrack packed into an int
*/
public int nextInt() {
PositionOnTrack tempP = new PositionOnTrack(trackExplorer.getPosition());
int x = tempP.getX();
int y = tempP.getY();
ImPoint targetPoint = stopsHandler.arrivesAtPoint(x, y);
int currentPosition = tempP.getOpposite().toInt();
ReadOnlyWorld world = trackExplorer.getWorld();
PositionOnTrack[] t = FlatTrackExplorer.getPossiblePositions(world,
targetPoint);
int[] targets = new int[t.length];
for (int i = 0; i < t.length; i++) {
int target = t[i].getOpposite().toInt();
if (target == currentPosition) {
stopsHandler.updateTarget();
}
targets[i] = target;
}
FlatTrackExplorer tempExplorer = new FlatTrackExplorer(world, tempP);
int next = pathFinder.findstep(currentPosition, targets, tempExplorer);
if (next == IncrementalPathFinder.PATH_NOT_FOUND) {
trackExplorer.nextEdge();
trackExplorer.moveForward();
return trackExplorer.getVertexConnectedByEdge();
}
tempP.setValuesFromInt(next);
tempP = tempP.getOpposite();
int nextPosition = tempP.toInt();
trackExplorer.setPosition(nextPosition);
mr.processMove(stopsHandler.getMoves());
return nextPosition;
}
}

TileSetFactoryImpl

Full name: jfreerails.server.TileSetFactoryImpl

Documentation

/**
* This class adds cargo and terrain types defined in an XML file to a World
* object.
*
* @author Luke
*
*/

Source Code

/**
* This class adds cargo and terrain types defined in an XML file to a World
* object.
*
* @author Luke
*
*/
public class TileSetFactoryImpl implements TileSetFactory {
public void addTerrainTileTypesList(World w) {
try {
java.net.URL url = RunTypesParser.class
.getResource("/jfreerails/data/cargo_and_terrain.xml");
CargoAndTerrainParser.parse(url, new CargoAndTerrainHandlerImpl(w));
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException();
}
}
}

TrainMaintenanceMoveGenerator

Full name: jfreerails.server.TrainMaintenanceMoveGenerator

Documentation

/**
* This class iterates over the entries in the BankAccount and counts the number
* of trains, then calculates the cost of maintenance.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* This class iterates over the entries in the BankAccount and counts the number
* of trains, then calculates the cost of maintenance.
*
* @author Luke Lindsay
*
*/
public class TrainMaintenanceMoveGenerator {
private final MoveReceiver moveReceiver;
public TrainMaintenanceMoveGenerator(MoveReceiver mr) {
this.moveReceiver = mr;
}
private static AddTransactionMove generateMove(World w,
FreerailsPrincipal principal) {
NonNullElements trains = new NonNullElements(KEY.TRAINS, w, principal);
int numberOfTrains = trains.size();
long amount = numberOfTrains * 5000;
Transaction t = new Bill(new Money(amount),
Transaction.Category.TRAIN_MAINTENANCE);
return new AddTransactionMove(principal, t);
}
public void update(World w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
Move m = generateMove(w, principal);
moveReceiver.processMove(m);
}
}
}

ServerGameModelImpl

Full name: jfreerails.server.ServerGameModelImpl

Documentation

/**
* A ServerGameModel that contains the automations used in the actual game.
*
* @author Luke
*
*/

Source Code

/**
* A ServerGameModel that contains the automations used in the actual game.
*
* @author Luke
*
*/
public class ServerGameModelImpl implements ServerGameModel {
private static final long serialVersionUID = 3978144352788820021L;
public World world;
private transient CalcSupplyAtStations calcSupplyAtStations;
private TrainUpdater tb;
private String[] passwords;
/**
* List of the ServerAutomaton objects connected to this game.
*/
private final Vector<ServerAutomaton> serverAutomata;
/**
* Number of ticks since the last time we did an infrequent update.
*/
private int ticksSinceUpdate = 0;
private transient long nextModelUpdateDue;
private transient MoveReceiver moveExecuter;
public ServerGameModelImpl() {
this(null, new Vector<ServerAutomaton>());
}
public ServerGameModelImpl( World w,
Vector<ServerAutomaton> serverAutomata) {
this.world = w;
this.serverAutomata = serverAutomata;
nextModelUpdateDue = System.currentTimeMillis();
}
/** This is called on the last tick of each year. */
private void yearEnd() {
TrackMaintenanceMoveGenerator tmmg = new TrackMaintenanceMoveGenerator(
moveExecuter);
tmmg.update(world);
TrainMaintenanceMoveGenerator trainMaintenanceMoveGenerator = new TrainMaintenanceMoveGenerator(
moveExecuter);
trainMaintenanceMoveGenerator.update(world);
InterestChargeMoveGenerator interestChargeMoveGenerator = new InterestChargeMoveGenerator(
moveExecuter);
interestChargeMoveGenerator.update(world);
// Grow cities.
WorldDiffs wd = new WorldDiffs(world);
CityTilePositioner ctp = new CityTilePositioner(wd);
ctp.growCities();
WorldDiffMove move = new WorldDiffMove(world, wd, WorldDiffMove.Cause.YearEnd);
moveExecuter.processMove(move);
}
/** This is called at the start of each new month. */
private void monthEnd() {
calcSupplyAtStations.doProcessing();
CargoAtStationsGenerator cargoAtStationsGenerator = new CargoAtStationsGenerator();
cargoAtStationsGenerator.update(world, moveExecuter);
}
private void updateGameTime() {
moveExecuter.processMove(TimeTickMove.getMove(world));
}
/**
*
*/
public synchronized void update() {
long frameStartTime = System.currentTimeMillis();
while (nextModelUpdateDue <= frameStartTime) {
/*
* First do the things that need doing whether or not the game is
* paused.
*/
tb.buildTrains(world);
int gameSpeed = ((GameSpeed) world.get(ITEM.GAME_SPEED)).getSpeed();
if (gameSpeed > 0) {
/*
* Update the time first, since other updates might need to know
* the current time.
*/
updateGameTime();
// now do the other updates
tb.moveTrains(world);
// Check whether we are about to start a new year..
GameTime time = world.currentTime();
GameCalendar calendar = (GameCalendar) world.get(ITEM.CALENDAR);
int yearNextTick = calendar.getYear(time.getTicks() + 1);
int yearThisTick = calendar.getYear(time.getTicks());
if (yearThisTick != yearNextTick) {
yearEnd();
}
// And a new month..
int monthThisTick = calendar.getMonth(time.getTicks());
int monthNextTick = calendar.getMonth(time.getTicks() + 1);
if (monthNextTick != monthThisTick) {
monthEnd();
}
/* calculate "ideal world" time for next tick */
nextModelUpdateDue = nextModelUpdateDue + (1000 / gameSpeed);
// int delay = (int)(nextModelUpdateDue - frameStartTime);
//
// /* wake up any waiting client threads - we could be
// * more aggressive, and only notify them if delay > 0? */
// this.notifyAll();
//
// try {
// if (delay > 0) {
// this.wait(delay);
// } else {
// this.wait(1);
// }
// } catch (InterruptedException e) {
// // do nothing
// }
ticksSinceUpdate++;
} else {
// try {
// //When the game is frozen we don't want to be spinning in a
// //loop.
// Thread.sleep(200);
// } catch (InterruptedException e) {
// // do nothing
// }
nextModelUpdateDue = System.currentTimeMillis();
}
}
}
public void write(ObjectOutputStream objectOut) throws IOException {
objectOut.writeObject(world);
objectOut.writeObject(serverAutomata);
/**
* save player private data
*/
for (int i = 0; i < world.getNumberOfPlayers(); i++) {
Player player = world.getPlayer(i);
player.saveSession(objectOut);
}
}
public void init(MoveReceiver newMoveExecuter) {
this.moveExecuter = newMoveExecuter;
tb = new TrainUpdater(newMoveExecuter);
calcSupplyAtStations = new CalcSupplyAtStations(world, newMoveExecuter);
for (int i = 0; i < serverAutomata.size(); i++) {
serverAutomata.get(i).initAutomaton(newMoveExecuter);
}
tb.initAutomaton(newMoveExecuter);
nextModelUpdateDue = System.currentTimeMillis();
}
public World getWorld() {
return world;
}
public void setWorld(World w, String[] passwords) {
this.world = w;
this.serverAutomata.clear();
this.passwords = passwords.clone();
}
public String[] getPasswords() {
return passwords.clone();
}
}

TrackMaintenanceMoveGenerator

Full name: jfreerails.server.TrackMaintenanceMoveGenerator

Documentation

/**
* This class iterates over the entries in the BankAccount and counts the number
* of units of each track type, then calculates the cost of maintenance.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* This class iterates over the entries in the BankAccount and counts the number
* of units of each track type, then calculates the cost of maintenance.
*
* @author Luke Lindsay
*
*/
public class TrackMaintenanceMoveGenerator {
private final MoveReceiver moveReceiver;
public TrackMaintenanceMoveGenerator(MoveReceiver mr) {
this.moveReceiver = mr;
}
public static AddTransactionMove generateMove(World w,
FreerailsPrincipal principal, Transaction.Category category) {
if (TRACK_MAINTENANCE != category && STATION_MAINTENANCE != category) {
throw new IllegalArgumentException(String.valueOf(category));
}
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
w, principal);
aggregator.setCategory(TRACK);
long amount = 0;
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
long maintenanceCost = trackRule.getMaintenanceCost().getAmount();
// Is the track type the category we are interested in?
boolean rightType = TRACK_MAINTENANCE == category ? !trackRule
.isStation() : trackRule.isStation();
if (rightType) {
aggregator.setType(i);
amount += maintenanceCost * aggregator.calculateQuantity()
/ TrackConfiguration.LENGTH_OF_STRAIGHT_TRACK_PIECE;
}
}
Transaction t = new Bill(new Money(amount), category);
return new AddTransactionMove(principal, t);
}
public void update(World w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
Move m = generateMove(w, principal, TRACK_MAINTENANCE);
moveReceiver.processMove(m);
m = generateMove(w, principal, STATION_MAINTENANCE);
moveReceiver.processMove(m);
}
}
}

InterestChargeMoveGenerator

Full name: jfreerails.server.InterestChargeMoveGenerator

Documentation

/**
* This class iterates over the entries in the BankAccount and counts the number
* of outstanding bonds, then calculates the interest due.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* This class iterates over the entries in the BankAccount and counts the number
* of outstanding bonds, then calculates the interest due.
*
* @author Luke Lindsay
*
*/
public class InterestChargeMoveGenerator {
private final MoveReceiver moveReceiver;
public InterestChargeMoveGenerator(MoveReceiver mr) {
this.moveReceiver = mr;
}
private static AddTransactionMove generateMove(World w,
FreerailsPrincipal principal) {
long interestDue = 0;
for (int i = 0; i < w.getNumberOfTransactions(principal); i++) {
Transaction t = w.getTransaction(principal, i);
if (t instanceof BondTransaction) {
BondTransaction bt = (BondTransaction) t;
int interestRate = bt.getType();
long bondAmount = BondTransaction.BOND_VALUE_ISSUE.getAmount();
interestDue += (interestRate * bondAmount / 100)
* bt.getQuantity();
}
}
Transaction t = new Bill(new Money(interestDue),
Transaction.Category.INTEREST_CHARGE);
return new AddTransactionMove(principal, t);
}
public void update(World w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
Move m = generateMove(w, principal);
moveReceiver.processMove(m);
}
}
}

MapFactory

Full name: jfreerails.server.MapFactory

Documentation

/**
* This class has a static method that converts an image file into a map.
*
* @author Luke
* @author Scott Bennett (Updated 23rd Jan 2004)
*
* Implemented Terrain Randomisation to randomly position the terrain types for
* each tile on the map.
*/

Source Code

/**
* This class has a static method that converts an image file into a map.
*
* @author Luke
* @author Scott Bennett (Updated 23rd Jan 2004)
*
* Implemented Terrain Randomisation to randomly position the terrain types for
* each tile on the map.
*/
public class MapFactory {
/*
* create a vector to keep track of what terrain types to 'clump'
*/
private static final Vector<Integer> countryTypes = new Vector<Integer>();
private static final Vector<Integer> non_countryTypes = new Vector<Integer>();
private static WorldImpl world;
public static void setupMap(URL map_url, WorldImpl w,
FreerailsProgressMonitor pm) {
// Setup progress monitor..
pm.setValue(0);
world = w;
Image mapImage = (new ImageIcon(map_url)).getImage();
Rectangle mapRect = new java.awt.Rectangle(0, 0, mapImage
.getWidth(null), mapImage.getHeight(null));
BufferedImage mapBufferedImage = new BufferedImage(mapRect.width,
mapRect.height, BufferedImage.TYPE_INT_ARGB);
Graphics g = mapBufferedImage.getGraphics();
g.drawImage(mapImage, 0, 0, null);
w.setupMap(mapRect.width, mapRect.height);
pm.nextStep(mapRect.width);
HashMap<Integer, Integer> rgb2TerrainType = new HashMap<Integer, Integer>();
for (int i = 0; i < w.size(SKEY.TERRAIN_TYPES); i++) {
TerrainType tilemodel = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
rgb2TerrainType.put(tilemodel.getRGB(), i);
}
TerrainType terrainTypeTile;
for (int c = 0; c < w.size(SKEY.TERRAIN_TYPES); c++) {
terrainTypeTile = (TerrainType) w.get(SKEY.TERRAIN_TYPES, c);
if (terrainTypeTile.getCategory().equals(
TerrainType.Category.Country)) {
if ((!terrainTypeTile.getTerrainTypeName().equals("Clear"))) {
countryTypes.add(new Integer(c));
}
}
if (terrainTypeTile.getCategory()
.equals(TerrainType.Category.Ocean)
|| terrainTypeTile.getCategory().equals(
TerrainType.Category.River)
|| terrainTypeTile.getCategory().equals(
TerrainType.Category.Hill)) {
non_countryTypes.add(new Integer(c));
}
}
TerrainRandomiser terrainRandomiser = new TerrainRandomiser(
countryTypes, non_countryTypes);
/*
* create vector to keep track of terrain randomisation 'clumping'
*/
Vector<RandomTerrainValue> locations = new Vector<RandomTerrainValue>();
for (int x = 0; x < mapRect.width; x++) {
pm.setValue(x);
for (int y = 0; y < mapRect.height; y++) {
int rgb = mapBufferedImage.getRGB(x, y);
FreerailsTile tile;
Integer type = rgb2TerrainType.get(rgb);
if (null == type) {
throw new NullPointerException(
"There is no terrain type mapped to rgb value "
+ rgb + " at location " + x + ", " + y);
}
tile = FreerailsTile.getInstance(terrainRandomiser
.getNewType(type.intValue()));
if (countryTypes.contains(tile.getTerrainTypeID())) {
locations.add(new RandomTerrainValue(x, y, tile
.getTerrainTypeID()));
}
w.setTile(x, y, tile);
}
}
for (int i = 0; i < locations.size(); i++) {
RandomTerrainValue rtv = locations.elementAt(i);
FreerailsTile tile = FreerailsTile.getInstance(rtv.getType());
int x = rtv.getX();
int y = rtv.getY();
int val = 3;
double prob = 0.75;
if (w.boundsContain(x - val, y - val)
&& w.boundsContain(x + val, y + val)) {
for (int m = x - val; m < x + val; m++) {
for (int n = y - val; n < y + val; n++) {
if (Math.random() > prob) {
setTile(m, n, tile);
}
}
}
}
}
}
private static void setTile(int x, int y, FreerailsTile tile) {
if (!non_countryTypes.contains(new Integer(((FreerailsTile) world
.getTile(x, y)).getTerrainTypeID()))) {
world.setTile(x, y, tile);
}
}
}

Methods

RandomTerrainValue

Full name: jfreerails.server.RandomTerrainValue

Documentation

/**
* Stores a location and terrain type.
*
* @author Scott?
*/

Source Code

/**
* Stores a location and terrain type.
*
* @author Scott?
*/
public class RandomTerrainValue {
private final int x;
private final int y;
private final int terrainType;
public RandomTerrainValue(int x, int y, int tt) {
this.x = x;
this.y = y;
this.terrainType = tt;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getType() {
return terrainType;
}
}

TerrainRandomiser

Full name: jfreerails.server.TerrainRandomiser

Documentation

/**
* Class to randomly select a terrain type for a terrain tile.
*
* TerrainRandomiser.java
*
* @author Scott Bennett Created on 23rd Jan 2004 The
* Terrain Types are: 0) City (Urban) 1) Refinery (Industry) 2) Village
* (Urban) 3) Factory (Industry) 4) Clear (Country) 5) Farm (Country) 6)
* Desert (Country) 7) Ocean (Ocean) 8) Harbour (Ocean) 9) Stock-Yard
* (Industry) 10) Food_Proc._Plant (Industry) 11) Cattle_Ranch
* (Resource) 12) Grain_Elevator (Resource) 13) Oil_Well (Resource) 14)
* Lumber_Mill (Resource) 15) Sugar_Plant. (Resource) 16) River (River)
* 17) Landing (River) 18) Terminal (Special) 19) Jungle (Country) 20)
* Hills (Hill) 21) Foothills (Hill) 22) Mountain (Hill)
*/

Source Code

/**
* Class to randomly select a terrain type for a terrain tile.
*
* TerrainRandomiser.java
*
* @author Scott Bennett Created on 23rd Jan 2004 The
* Terrain Types are: 0) City (Urban) 1) Refinery (Industry) 2) Village
* (Urban) 3) Factory (Industry) 4) Clear (Country) 5) Farm (Country) 6)
* Desert (Country) 7) Ocean (Ocean) 8) Harbour (Ocean) 9) Stock-Yard
* (Industry) 10) Food_Proc._Plant (Industry) 11) Cattle_Ranch
* (Resource) 12) Grain_Elevator (Resource) 13) Oil_Well (Resource) 14)
* Lumber_Mill (Resource) 15) Sugar_Plant. (Resource) 16) River (River)
* 17) Landing (River) 18) Terminal (Special) 19) Jungle (Country) 20)
* Hills (Hill) 21) Foothills (Hill) 22) Mountain (Hill)
*/
public class TerrainRandomiser {
private final Vector<Integer> terrainTypes;
private final Vector<Integer> non_terrainTypes;
private final double CLEAR_PERCENTAGE = 0.98; // ie. % of map that is
// clear (on avg.)
public TerrainRandomiser(Vector<Integer> num, Vector<Integer> num2) {
terrainTypes = num;
non_terrainTypes = num2;
}
public int getNewType(int type) {
int newType = type;
double value;
double divide = 1.0 / terrainTypes.size();
// allow any terrain type to be drawn over except those listed in
// non_terrainTypes
if (!non_terrainTypes.contains(new Integer(newType))) {
if (Math.random() < CLEAR_PERCENTAGE) {
// make the tile Clear
return 4;
}
value = Math.random();
/*
* at the moment, this logic produces a balanced and even
* distribution of the different country tiles (currently 3).
* somehow it would be better to have the actual proportions of
* Farms, Jungle and Desert etc vary. dunno how.
*/
for (int i = 0; i < terrainTypes.size(); i++) {
if ((value > (i * divide)) && (value <= ((i + 1) * divide))) {
return terrainTypes.elementAt(i).intValue();
}
}
}
return newType;
}
}

CityEconomicModel

Full name: jfreerails.server.CityEconomicModel

Documentation

/**
* This class is lets the server analyse and alter cities.
*
* @author Luke
*
*/

Source Code

/**
* This class is lets the server analyse and alter cities.
*
* @author Luke
*
*/
class CityEconomicModel {
/** Stores a tile type and its location. */
private class Tile {
final Point p;
final TerrainType type;
public Tile(final Point p, final TerrainType type) {
this.p = p;
this.type = type;
}
}
final ArrayList<Tile> urbanTiles = new ArrayList<Tile>();
final ArrayList<Tile> industryTiles = new ArrayList<Tile>();
final ArrayList<TerrainType> industriesNotAtCity = new ArrayList<TerrainType>();
final ArrayList<Tile> resourceTiles = new ArrayList<Tile>();
final ArrayList<Point> clearTiles = new ArrayList<Point>();
/** The number of stations within this city's bounds. */
int stations = 0;
void addTile(TerrainType type) {
Random rand = new Random();
// Pick a spot at random at which to place the tile.
if (clearTiles.size() > 0) {
int tilePos = rand.nextInt(clearTiles.size());
Point p = clearTiles.remove(tilePos);
if (type.getCategory().equals(TerrainType.Category.Urban)) {
urbanTiles.add(new Tile(p, type));
} else if (type.getCategory().equals(TerrainType.Category.Industry)) {
industryTiles.add(new Tile(p, type));
industriesNotAtCity.remove(type);
} else if (type.getCategory().equals(TerrainType.Category.Country)) {
throw new IllegalArgumentException(
"call remove(.) to replace a city tile with a country tile!");
} else if (type.getCategory().equals(TerrainType.Category.Resource)) {
resourceTiles.add(new Tile(p, type));
}
}
}
void loadFromMap(ReadOnlyWorld w, int cityID) {
/* Reset lists of tiles. */
urbanTiles.clear();
industryTiles.clear();
clearTiles.clear();
resourceTiles.clear();
/* Set up the list of industries not at the city. */
industriesNotAtCity.clear();
for (int i = 0; i < w.size(SKEY.TERRAIN_TYPES); i++) {
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
if (type.getCategory().equals(TerrainType.Category.Industry)) {
industriesNotAtCity.add(type);
}
}
stations = 0;
/* Identify city's bounds. */
Rectangle mapRect = new Rectangle(0, 0, w.getMapWidth(), w
.getMapHeight());
CityModel city = (CityModel) w.get(SKEY.CITIES, cityID);
Rectangle cityArea = new Rectangle(city.getCityX() - 3,
city.getCityY() - 3, 7, 7);
cityArea = cityArea.intersection(mapRect);
/* Count tile types. */
for (int x = cityArea.x; x < cityArea.x + cityArea.width; x++) {
for (int y = cityArea.y; y < cityArea.y + cityArea.height; y++) {
FreerailsTile tile = (FreerailsTile) w.getTile(x, y);
/* Count the number of stations at the city. */
if (tile.getTrackPiece().getTrackRule().isStation()) {
stations++;
}
int terrainTypeNumber = tile.getTerrainTypeID();
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES,
terrainTypeNumber);
if (type.getCategory().equals(TerrainType.Category.Urban)) {
urbanTiles.add(new Tile(new Point(x, y), type));
} else if (type.getCategory().equals(
TerrainType.Category.Industry)) {
industryTiles.add(new Tile(new Point(x, y), type));
industriesNotAtCity.remove(type);
} else if (type.getCategory().equals(
TerrainType.Category.Country)) {
clearTiles.add(new Point(x, y));
} else if (type.getCategory().equals(
TerrainType.Category.Resource)) {
resourceTiles.add(new Tile(new Point(x, y), type));
}
}
}
}
int size() {
return this.urbanTiles.size() + this.industryTiles.size()
+ this.resourceTiles.size();
}
void write2map(World w) {
for (int i = 0; i < urbanTiles.size(); i++) {
writeTile(w, urbanTiles.get(i));
}
for (int i = 0; i < industryTiles.size(); i++) {
writeTile(w, industryTiles.get(i));
}
for (int i = 0; i < resourceTiles.size(); i++) {
writeTile(w, resourceTiles.get(i));
}
}
private void writeTile(World w, Tile tile) {
int type = 0;
while (!w.get(SKEY.TERRAIN_TYPES, type).equals(tile.type)) {
type++;
}
int x = tile.p.x;
int y = tile.p.y;
FreerailsTile fTile = (FreerailsTile) w.getTile(x, y);
fTile = FreerailsTile.getInstance(type, fTile.getTrackPiece());
w.setTile(x, y, fTile);
}
}

InputCityNames

Full name: jfreerails.server.InputCityNames

Documentation

/**
* Class that calls the object to input the City names and co-ords from an xml
* file.
*
* @author Scott Bennett Date: 31st March 2003
*/

Source Code

/**
* Class that calls the object to input the City names and co-ords from an xml
* file.
*
* @author Scott Bennett Date: 31st March 2003
*/
public class InputCityNames {
public static void readCityNames(World w, URL filename) throws SAXException {
InputSource is = new InputSource(filename.toString());
DefaultHandler handler = new CitySAXParser(w);
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(is, handler);
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
}
}
}

Methods

CargoAtStationsGenerator

Full name: jfreerails.server.CargoAtStationsGenerator

Documentation

/**
* This class loops over the list of stations and adds cargo depending on what
* the surrounding tiles supply.
*
* @author Luke
*
*/

Source Code

/**
* This class loops over the list of stations and adds cargo depending on what
* the surrounding tiles supply.
*
* @author Luke
*
*/
public class CargoAtStationsGenerator implements FreerailsServerSerializable {
private static final long serialVersionUID = 3834596504072959796L;
public CargoAtStationsGenerator() {
}
/** Call this method once a month. */
public void update(World w, MoveReceiver moveReceiver) {
for (int k = 0; k < w.getNumberOfPlayers(); k++) {
FreerailsPrincipal principal = w.getPlayer(k).getPrincipal();
NonNullElements nonNullStations = new NonNullElements(KEY.STATIONS,
w, principal);
while (nonNullStations.next()) {
StationModel station = (StationModel) nonNullStations
.getElement();
SupplyAtStation supply = station.getSupply();
ImmutableCargoBundle cargoBundle = (ImmutableCargoBundle) w
.get(principal, KEY.CARGO_BUNDLES,
station.getCargoBundleID());
MutableCargoBundle before = new MutableCargoBundle(cargoBundle);
MutableCargoBundle after = new MutableCargoBundle(cargoBundle);
int stationNumber = nonNullStations.getIndex();
/*
* Get the iterator from a copy to avoid a
* ConcurrentModificationException if the amount gets set to
* zero and the CargoBatch removed from the cargo bundle. LL
*/
Iterator<CargoBatch> it = after.toImmutableCargoBundle()
.cargoBatchIterator();
while (it.hasNext()) {
CargoBatch cb = it.next();
int amount = after.getAmount(cb);
if (amount > 0) {
// (23/24)^12 = 0.60
after.setAmount(cb, amount * 23 / 24);
}
}
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
int amountSupplied = supply.getSupply(i);
if (amountSupplied > 0) {
CargoBatch cb = new CargoBatch(i, station.x, station.y,
0, stationNumber);
int amountAlready = after.getAmount(cb);
// Obtain the month
GameTime time = w.currentTime();
GameCalendar calendar = (GameCalendar) w
.get(ITEM.CALENDAR);
int month = calendar.getMonth(time.getTicks());
int amountAfter = calculateAmountToAdd(amountSupplied,
month)
+ amountAlready;
after.setAmount(cb, amountAfter);
}
}
Move m = new ChangeCargoBundleMove(before
.toImmutableCargoBundle(), after
.toImmutableCargoBundle(), station.getCargoBundleID(),
principal);
moveReceiver.processMove(m);
}
}
}
int calculateAmountToAdd(int amountSuppliedPerYear, int month) {
// Note, jan is month 0.
int totalAtMonthEnd = amountSuppliedPerYear * (month + 1) / 12;
int totalAtMonthStart = amountSuppliedPerYear * (month) / 12;
int amount = totalAtMonthEnd - totalAtMonthStart;
return amount;
}
}

OldWorldImpl

Full name: jfreerails.server.OldWorldImpl

Documentation

/**
* This class sets up a World object.
*
* @author luke
*/

Source Code

/**
* This class sets up a World object.
*
* @author luke
*/
public class OldWorldImpl {
/** Note, the map name is converted to lower case and any spaces
* are replaced with underscores.
*
*/
public static World createWorldFromMapFile(String mapName,
FreerailsProgressMonitor pm) {
mapName = mapName.toLowerCase();
mapName = mapName.replace(' ', '_');
pm.setValue(0);
pm.nextStep(7);
int progress = 0;
TileSetFactory tileFactory = new TileSetFactoryImpl();
pm.setValue(++progress);
WorldImpl w = new WorldImpl();
pm.setValue(++progress);
WagonAndEngineTypesFactory wetf = new WagonAndEngineTypesFactory();
pm.setValue(++progress);
wetf.addTypesToWorld(w);
pm.setValue(++progress);
tileFactory.addTerrainTileTypesList(w);
pm.setValue(++progress);
URL track_xml_url = OldWorldImpl.class
.getResource("/jfreerails/data/track_tiles.xml");
Track_TilesHandlerImpl trackSetFactory = new Track_TilesHandlerImpl(
track_xml_url);
pm.setValue(++progress);
trackSetFactory.addTrackRules(w);
pm.setValue(++progress);
// Load the terrain map
URL map_url = OldWorldImpl.class.getResource("/jfreerails/data/"
+ mapName + ".png");
MapFactory.setupMap(map_url, w, pm);
// Load the city names
URL cities_xml_url = OldWorldImpl.class.getResource("/jfreerails/data/"
+ mapName + "_cities.xml");
try {
InputCityNames.readCityNames(w, cities_xml_url);
} catch (SAXException e) {
}
// Randomly position the city tiles
CityTilePositioner ctp = new CityTilePositioner(w);
ctp.initCities();
// Set the time..
w.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
w.setTime(new GameTime(0));
w.set(ITEM.GAME_SPEED, new GameSpeed(10));
w.set(ITEM.GAME_RULES, GameRules.DEFAULT_RULES);
/*
* Note, money used to get added to player accounts here, now it is done
* when players are added. See AddPlayerMove
*/
return w;
}
}

MapCustomizer

Full name: jfreerails.server.MapCustomizer

Documentation

/**
* Provides methods to customize a map by adding track, stations and trains.
* Intended for use in unit tests.
*
* @author Luke
*/

Source Code

/**
* Provides methods to customize a map by adding track, stations and trains.
* Intended for use in unit tests.
*
* @author Luke
*/
public class MapCustomizer {
public final World w;
private final TrackMoveProducer producer;
private final TrackPathFinder pathFinder;
private final StationBuilder stationBuilder;
private final BuildTrackStrategy bts;
public MapCustomizer() {
this(MapFixtureFactory2.getCopy());
}
public MapCustomizer(World w) {
this.w = w;
MoveExecutor me = new SimpleMoveExecutor(w, 0);
ModelRoot mr = new ModelRootImpl();
producer = new TrackMoveProducer(me, w, mr);
FreerailsPrincipal principal = w.getPlayer(0).getPrincipal();
pathFinder = new TrackPathFinder(w, principal);
stationBuilder = new StationBuilder(me);
int terminalTypeID = stationBuilder.getTrackTypeID("terminal");
stationBuilder.setStationType(terminalTypeID);
bts = BuildTrackStrategy.getDefault(w);
}
public MapCustomizer buildTrack(ImPoint a, ImPoint b) throws PathNotFoundException {
pathFinder.setupSearch(a, b, bts);
pathFinder.search(-1);
List<ImPoint> pathAsPoints = pathFinder.pathAsPoints();
ImPoint from = a;
for (int i = 0; i < pathAsPoints.size(); i++) {
ImPoint to = pathAsPoints.get(i);
Step vector = Step.getInstance(to.x - from.x, to.y
- from.y);
FreerailsTile tile = (FreerailsTile) w.getTile(
from.x, from.y);
if (!tile.getTrackPiece().getTrackConfiguration().contains(vector)) {
producer.buildTrack(from, vector);
}
from = to;
}
return this;
}
public MapCustomizer buildStation(ImPoint a) {
MoveStatus ms = stationBuilder.buildStation(a);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
return this;
}
public MapCustomizer buildTrain(ImPoint a, int... stops) {
FreerailsPrincipal principal = w.getPlayer(0).getPrincipal();
MutableSchedule s = new MutableSchedule();
for (int stop : stops) {
s.addOrder(new TrainOrdersModel(stop, null, false, true));
}
ImmutableSchedule defaultSchedule = s.toImmutableSchedule();
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(),
a, principal, defaultSchedule);
Move m = preMove.generateMove(w);
MoveStatus status = m.doMove(w, Player.AUTHORITATIVE);
if (!status.ok) {
throw new IllegalStateException(status.message);
}
return this;
}
/**
* Returns -1 if no station here or the id of the station if one is
* present.
*/
public int getStationId(ImPoint location) {
FreerailsPrincipal principal = w.getPlayer(0).getPrincipal();
FreerailsTile tile = (FreerailsTile) w.getTile(location.x, location.y);
TrackRule trackRule = tile.getTrackPiece().getTrackRule();
if (trackRule.isStation()
&& tile.getTrackPiece().getOwnerID() == w.getID(principal)) {
for (int i = 0; i < w.size(principal, KEY.STATIONS); i++) {
StationModel station = (StationModel) w.get(principal,
KEY.STATIONS, i);
if (null != station && station.getLocation().equals(location)) {
return i;
}
}
throw new IllegalStateException();
} else {
return -1;
}
}
}

CalcSupplyAtStations

Full name: jfreerails.server.CalcSupplyAtStations

Documentation

/**
* This class loops through all of the known stations and recalculates the
* cargoes that they supply, demand, and convert.
*
* @author Scott Bennett Created: 19th May 2003
*/

Source Code

/**
* This class loops through all of the known stations and recalculates the
* cargoes that they supply, demand, and convert.
*
* @author Scott Bennett Created: 19th May 2003
*/
public class CalcSupplyAtStations {
private final World w;
private final MoveReceiver moveReceiver;
/**
*
* Constructor, currently called from GUIComponentFactory.
*
* @param world
* The World object that contains all about the game world
*
*/
public CalcSupplyAtStations(World world, MoveReceiver mr) {
this.w = world;
this.moveReceiver = mr;
}
/**
*
* Loop through each known station, call calculations method.
*
*/
public void doProcessing() {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
NonNullElements iterator = new NonNullElements(KEY.STATIONS, w,
principal);
while (iterator.next()) {
StationModel stationBefore = (StationModel) iterator
.getElement();
CalcCargoSupplyRateAtStation supplyRate;
supplyRate = new CalcCargoSupplyRateAtStation(w,
stationBefore.x, stationBefore.y);
StationModel stationAfter = supplyRate
.calculations(stationBefore);
if (!stationAfter.equals(stationBefore)) {
Move move = new ChangeStationMove(iterator.getIndex(),
stationBefore, stationAfter, principal);
this.moveReceiver.processMove(move);
}
}
}
}
}

TrainUpdater

Full name: jfreerails.server.TrainUpdater

Documentation

/**
* This class is used by the server to generate moves that add trains, move
* trains, and handle stops at stations. Note, the client should not use this
* class to build trains, instead it should request that a train gets built by
* setting production at an engine shop.
*
* @author Luke Lindsay 13-Oct-2002
*
*/

Source Code

/**
* This class is used by the server to generate moves that add trains, move
* trains, and handle stops at stations. Note, the client should not use this
* class to build trains, instead it should request that a train gets built by
* setting production at an engine shop.
*
* @author Luke Lindsay 13-Oct-2002
*
*/
public class TrainUpdater implements ServerAutomaton {
private static final long serialVersionUID = 3258410646839243577L;
/**
* @return a move that initialises the trains schedule.
*/
public static Move initTarget(TrainModel train, int trainID,
ImmutableSchedule currentSchedule, FreerailsPrincipal principal) {
Vector<Move> moves = new Vector<Move>();
int scheduleID = train.getScheduleID();
MutableSchedule schedule = new MutableSchedule(currentSchedule);
ImInts wagonsToAdd = schedule.getWagonsToAdd();
if (null != wagonsToAdd) {
int engine = train.getEngineType();
ChangeTrainMove move = ChangeTrainMove.generateMove(trainID, train,
engine, wagonsToAdd, principal);
moves.add(move);
}
schedule.gotoNextStation();
ImmutableSchedule newSchedule = schedule.toImmutableSchedule();
ChangeTrainScheduleMove move = new ChangeTrainScheduleMove(scheduleID,
currentSchedule, newSchedule, principal);
moves.add(move);
return new CompositeMove(moves.toArray(new Move[1]));
}
static TrainPositionOnMap setInitialTrainPosition(TrainModel train,
FreerailsPathIterator from) {
int trainLength = train.getLength();
PathWalker fromPathWalker = new PathWalkerImpl(from);
assert fromPathWalker.canStepForward();
fromPathWalker.stepForward(trainLength);
TrainPositionOnMap initialPosition = TrainPositionOnMap
.createInSameDirectionAsPath(fromPathWalker);
return initialPosition;
}
public static ImPoint[] trainPos2Tiles(TrainPositionOnMap pos) {
ImPoint[] returnValue = new ImPoint[pos.getLength()];
final int TILE_WIDTH = 30;
for (int i = 0; i < returnValue.length; i++) {
returnValue[i] = new ImPoint(pos.getX(i) / TILE_WIDTH, pos.getY(i)
/ TILE_WIDTH);
}
return returnValue;
}
private transient MoveReceiver moveReceiver;
public TrainUpdater(MoveReceiver mr) {
moveReceiver = mr;
if (null == mr) {
throw new NullPointerException();
}
}
public void buildTrain(int engineTypeId, ImInts wagons, ImPoint p,
FreerailsPrincipal principal, ReadOnlyWorld world) {
// If there are no wagons, setup an automatic schedule.
boolean autoSchedule = 0 == wagons.size();
ImmutableSchedule is = generateInitialSchedule(principal, world,
autoSchedule);
PreMove addTrain = new AddTrainPreMove(engineTypeId, wagons, p,
principal, is);
Move m = addTrain.generateMove(world);
moveReceiver.processMove(m);
}
// /**
// * Generates a composite move that adds a train to the train list, adds a
// * cargo bundle for the train to the cargo bundles list, and sets the
// * train's initial position. The move is sent to the moveProcessor and a
// * TrainMover object to update the trains position is returned.
// *
// * @param engineTypeId
// * type of the engine
// * @param wagons
// * array of wagon types
// * @param p
// * point at which to add train on map.
// *
// *
// */
// public TrainMover buildTrain(int engineTypeId, ImInts wagons, ImPoint p,
// FreerailsPrincipal principal, ReadOnlyWorld world) {
// /* Check that the specified position is on the track. */
// FreerailsTile tile = (FreerailsTile) world.getTile(p.x, p.y);
// if (NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER != tile.getTrackTypeID()) {
// /* Create the move that sets up the train's cargo bundle. */
// int cargoBundleId = world.size(principal, KEY.CARGO_BUNDLES);
// Move addCargoBundleMove = new AddCargoBundleMove(cargoBundleId,
// ImmutableCargoBundle.EMPTY_BUNDLE, principal);
//
// /* Create the train model object. */
// int scheduleId = world.size(principal, KEY.TRAIN_SCHEDULES);
//
// TrainModel train = new TrainModel(engineTypeId, wagons, scheduleId,
// cargoBundleId);
//
// /* Create the move that sets up the train's schedule. */
//
// // If there are no wagons, setup an automatic schedule.
// boolean autoSchedule = 0 == wagons.size();
//
// ImmutableSchedule is = generateInitialSchedule(principal, world,
// autoSchedule);
// int trainId = world.size(principal, KEY.TRAINS);
// Move setupScheduleMove = TrainUpdater.initTarget(train, trainId,
// is, principal);
//
// /* Create the move that sets the train's initial position. */
// FreerailsPathIterator from = getRandomPathToFollow(p, world);
// TrainPositionOnMap initialPosition = TrainUpdater
// .setInitialTrainPosition(train, from);
// Move positionMove = new InitialiseTrainPositionMove(trainId,
// initialPosition, principal);
//
// /* Determine the price of the train. */
// EngineType engineType = (EngineType) world.get(SKEY.ENGINE_TYPES,
// engineTypeId);
// Money price = engineType.getPrice();
//
// /* Create the move that adds the train to the train list. */
// AddTrainMove addTrainMove = AddTrainMove.generateMove(trainId,
// train, price, is, principal);
//
// /* Create a composite move made up of the moves created above. */
// Move compositeMove = new CompositeMove(new Move[] {
// addCargoBundleMove, addTrainMove, setupScheduleMove });
//
// /* Execute the move. */
// moveReceiver.processMove(compositeMove);
// moveReceiver.processMove(positionMove);
//
// /* Create a TrainMover to update the train's position. */
// TrainPathFinder tpf = getPathToFollow(p, world, trainId, principal);
// TrainMover trainMover = new TrainMover(tpf, world, trainId,
// principal);
//
// return trainMover;
// }
// throw new IllegalArgumentException("No track here (" + p.x + ", " + p.y
// + ") so cannot build train");
// }
/**
* Iterator over the stations and build trains at any that have their
* production field set.
*
*/
void buildTrains(ReadOnlyWorld world) {
for (int k = 0; k < world.getNumberOfPlayers(); k++) {
FreerailsPrincipal principal = world.getPlayer(k).getPrincipal();
for (int i = 0; i < world.size(principal, KEY.STATIONS); i++) {
StationModel station = (StationModel) world.get(principal,
KEY.STATIONS, i);
if (null != station) {
ImList<PlannedTrain> production = station
.getProduction();
if (production.size() > 0) {
ImPoint p = new ImPoint(station.x, station.y);
for (int j = 0; j < production.size(); j++) {
int engineType = production.get(j).getEngineType();
ImInts wagonTypes = production.get(j)
.getWagonTypes();
this.buildTrain(engineType, wagonTypes, p,
principal, world);
// TrainMover trainMover =
// this.buildTrain(engineType, wagonTypes, p,
// principal, world);
// this.addTrainMover(trainMover);
}
ChangeProductionAtEngineShopMove move = new ChangeProductionAtEngineShopMove(
production,
new ImList<PlannedTrain>(), i,
principal);
moveReceiver.processMove(move);
}
}
}
}
}
private ImmutableSchedule generateInitialSchedule(
FreerailsPrincipal principal, ReadOnlyWorld world,
boolean autoSchedule) {
WorldIterator wi = new NonNullElements(KEY.STATIONS, world, principal);
MutableSchedule s = new MutableSchedule();
// Add upto 4 stations to the schedule.
while (wi.next() && s.getNumOrders() < 5) {
TrainOrdersModel orders = new TrainOrdersModel(wi.getIndex(), null,
false, autoSchedule);
s.addOrder(orders);
}
s.setOrderToGoto(0);
ImmutableSchedule is = s.toImmutableSchedule();
return is;
}
public void initAutomaton(MoveReceiver mr) {
moveReceiver = mr;
}
void moveTrains(ReadOnlyWorld world) {
int time = world.currentTime().getTicks();
for (int k = 0; k < world.getNumberOfPlayers(); k++) {
FreerailsPrincipal principal = world.getPlayer(k).getPrincipal();
//If a train is moving, we want it to keep moving rather than stop
//to allow an already stationary train to start moving. To achieve this
//we process moving trains first.
ArrayList<Integer> movingTrains = new ArrayList<Integer>();
ArrayList<Integer> stoppedTrains = new ArrayList<Integer>();
for (int i = 0; i < world.size(principal, KEY.TRAINS); i++) {
TrainModel train = (TrainModel) world.get(principal,
KEY.TRAINS, i);
if (null == train) {
continue;
}
TrainAccessor ta = new TrainAccessor(world, principal, i);
if (ta.isMoving(time)) {
movingTrains.add(i);
} else {
stoppedTrains.add(i);
}
}
for (int trainId : movingTrains) {
moveTrain(world, principal, trainId);
}
for (int trainId : stoppedTrains) {
moveTrain(world, principal, trainId);
}
}
}
private void moveTrain(ReadOnlyWorld world, FreerailsPrincipal principal, int trainId) {
MoveTrainPreMove preMove = new MoveTrainPreMove(trainId, principal);
if (preMove.isUpdateDue(world)) {
TrainAccessor ta = new TrainAccessor(world, principal, trainId);
if (!ta.trackExists()) {
System.out.println("Track under train does not exist. Retiring train..");
this.retireTrain(world, principal, trainId);
} else {
Move m = preMove.generateMove(world);
moveReceiver.processMove(m);
}
}
}
private void retireTrain(ReadOnlyWorld world, FreerailsPrincipal principal, int trainId) {
Move m = RemoveTrainMove.getInstance(trainId, principal, world);
moveReceiver.processMove(m);
}
}

TileSetFactory

Full name: jfreerails.server.common.TileSetFactory

Documentation

/**
* This interface defines a method to add the terrain types to the world.
*
* @author Luke Lindsay 09 October 2001
*/

Source Code

/**
* This interface defines a method to add the terrain types to the world.
*
* @author Luke Lindsay 09 October 2001
*/
public interface TileSetFactory {
void addTerrainTileTypesList(World w);
}

RunTypesParser

Full name: jfreerails.server.parser.RunTypesParser

Documentation

/**
* The main method on this class uses CargoAndTerrainParser to the parse cargo
* and terrain types xml file - use it to test the parser and xml file work
* together.
*
* @author Luke
*/

Source Code

/**
* The main method on this class uses CargoAndTerrainParser to the parse cargo
* and terrain types xml file - use it to test the parser and xml file work
* together.
*
* @author Luke
*/
public class RunTypesParser {
private static final Logger logger = Logger.getLogger(RunTypesParser.class
.getName());
public static void main(String[] args) {
try {
java.net.URL url = RunTypesParser.class
.getResource("/jfreerails/data/cargo_and_terrain.xml");
CargoAndTerrainParser.parse(url, new CargoAndTerrainHandlerImpl(
new WorldImpl()));
logger.info("It worked");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Methods

Track_TilesHandlerImpl

Full name: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

/**
* Processes Track_TilesHandle events, generates track rules, and provides a
* methods to add the track rules to the world object.
*
* @author lindsal
* @version generated by FFJ XML module
* @see Track_TilesParser
*/

Source Code

/**
* Processes Track_TilesHandle events, generates track rules, and provides a
* methods to add the track rules to the world object.
*
* @author lindsal
* @version generated by FFJ XML module
* @see Track_TilesParser
*/
public class Track_TilesHandlerImpl implements Track_TilesHandler {
int maxConsequ;
protected List<TrackRule> ruleList;
protected jfreerails.world.track.TrackRuleProperties trackRuleProperties;
protected jfreerails.world.track.LegalTrackConfigurations legalTrackConfigurations;
protected ArrayList<String> legalTemplates;
protected HashSet<TerrainType.Category> terrainTypes;
protected LegalTrackPlacement legalTrackPlacement;
public void start_CanOnlyBuildOnTheseTerrainTypes(final Attributes meta)
throws SAXException {
terrainTypes = new HashSet<TerrainType.Category>();
}
public void end_CanOnlyBuildOnTheseTerrainTypes() throws SAXException {
legalTrackPlacement = new LegalTrackPlacement(terrainTypes,
LegalTrackPlacement.PlacementRule.ONLY_ON_THESE);
terrainTypes = null;
}
public void start_ListOfTrackPieceTemplates(final Attributes meta)
throws SAXException {
legalTemplates = new ArrayList<String>();
}
public void end_ListOfTrackPieceTemplates() throws SAXException {
legalTrackConfigurations = new jfreerails.world.track.LegalTrackConfigurations(
maxConsequ, legalTemplates);
legalTemplates = null;
}
public void start_ListOfLegalRoutesAcrossNode(final Attributes meta)
throws SAXException {
}
public void end_ListOfLegalRoutesAcrossNode() throws SAXException {
}
public void handle_LegalRouteAcrossNode(final Attributes meta)
throws SAXException {
}
public void start_CannotBuildOnTheseTerrainTypes(final Attributes meta)
throws SAXException {
terrainTypes = new java.util.HashSet<TerrainType.Category>();
}
public void end_CannotBuildOnTheseTerrainTypes() throws SAXException {
legalTrackPlacement = new LegalTrackPlacement(terrainTypes,
LegalTrackPlacement.PlacementRule.ANYWHERE_EXCEPT_ON_THESE);
terrainTypes = null;
}
public void start_TrackType(final Attributes meta) throws SAXException {
int rGBvalue;
String rgbString = meta.getValue("RGBvalue");
rGBvalue = Integer.parseInt(rgbString, 16);
/*
* We need to change the format of the rgb value to the same one as used
* by the the BufferedImage that stores the map. See
* jfreerails.common.Map
*/
rGBvalue = new java.awt.Color(rGBvalue).getRGB();
TrackRule.TrackCategories category = TrackRule.TrackCategories
.valueOf(meta.getValue("category"));
boolean enableDoubleTrack = Boolean.valueOf(
meta.getValue("doubleTrack")).booleanValue();
String typeName = meta.getValue("type");
maxConsequ = Integer.parseInt(meta.getValue("maxConsecuativePieces"));
String stationRadiusString = meta.getValue("stationRadius");
int stationRadius;
if (null != stationRadiusString) {
stationRadius = Integer.parseInt(stationRadiusString);
} else {
stationRadius = 0;
}
String priceString = meta.getValue("price");
int price = Integer.parseInt(priceString);
String fixedCostString = meta.getValue("fixedCost");
int fixedCost;
if (null != fixedCostString) {
fixedCost = Integer.parseInt(fixedCostString);
} else {
fixedCost = 0;
}
String maintenanceString = meta.getValue("maintenance");
int maintenance = Integer.parseInt(maintenanceString);
trackRuleProperties = new TrackRuleProperties(rGBvalue,
enableDoubleTrack, typeName, category, stationRadius, price,
maintenance, fixedCost);
}
public void end_TrackType() throws SAXException {
TrackRuleImpl trackRuleImpl = new jfreerails.world.track.TrackRuleImpl(
trackRuleProperties, legalTrackConfigurations,
legalTrackPlacement);
ruleList.add(trackRuleImpl);
legalTrackConfigurations = null;
trackRuleProperties = null;
legalTrackPlacement = null;
}
public void handle_TerrainType(final Attributes meta) throws SAXException {
TerrainType.Category cat = TerrainType.Category.valueOf(meta
.getValue("name"));
terrainTypes.add(cat);
}
public void start_Tiles(final Attributes meta) throws SAXException {
}
public void end_Tiles() throws SAXException {
// Sort the track tiles by category then price.
Collections.sort(ruleList);
}
public void start_TrackPieceTemplate(final Attributes meta)
throws SAXException {
legalTemplates.add(meta.getValue("trackTemplate"));
}
public void end_TrackPieceTemplate() throws SAXException {
// do nothing.
}
public void start_TrackSet(final Attributes meta) throws SAXException {
ruleList = new ArrayList<TrackRule>();
}
public void end_TrackSet() throws SAXException {
}
public Track_TilesHandlerImpl(java.net.URL trackXmlUrl) {
try {
Track_TilesParser.parse(trackXmlUrl, this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void addTrackRules(World w) {
for (int i = 0; i < this.ruleList.size(); i++) {
TrackRule r = ruleList.get(i);
w.add(SKEY.TRACK_RULES, r);
}
}
public List<TrackRule> getRuleList() {
return ruleList;
}
}

CargoAndTerrainHandler

Full name: jfreerails.server.parser.CargoAndTerrainHandler

Documentation

/**
* Defines methods to handle parsing the cargo and terrain types XML.
*
* @author Luke
* @version generated by NetBeans XML module
*/

Source Code

/**
* Defines methods to handle parsing the cargo and terrain types XML.
*
* @author Luke
* @version generated by NetBeans XML module
*/
public interface CargoAndTerrainHandler {
/**
* An empty element event handling method.
*
*/
public void handle_Converts(final Attributes meta) throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/
public void start_Tile(final Attributes meta) throws SAXException;
/**
* A container element end event handling method.
*
*/
public void end_Tile() throws SAXException;
/**
* An empty element event handling method.
*
*/
public void handle_Cargo(final Attributes meta) throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/
public void start_Cargo_Types(final Attributes meta) throws SAXException;
/**
* A container element end event handling method.
*
*/
public void end_Cargo_Types() throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/
public void start_Terrain_Types(final Attributes meta) throws SAXException;
/**
* A container element end event handling method.
*
*/
public void end_Terrain_Types() throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/
public void start_Types(final Attributes meta) throws SAXException;
/**
* A container element end event handling method.
*
*/
public void end_Types() throws SAXException;
/**
* An empty element event handling method.
*
*/
public void handle_Consumes(final Attributes meta) throws SAXException;
/**
* An empty element event handling method.
*
*/
public void handle_Produces(final Attributes meta) throws SAXException;
}

Track_TilesHandler

Full name: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* Defines methods to handle parsing the track types XML.
*
* @author lindsal
* @version generated by FFJ XML module
*/

Source Code

/**
* Defines methods to handle parsing the track types XML.
*
* @author lindsal
* @version generated by FFJ XML module
*/
public interface Track_TilesHandler {
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_CanOnlyBuildOnTheseTerrainTypes(final Attributes meta)
throws SAXException;
/**
* A container element end event handling method.
*/
void end_CanOnlyBuildOnTheseTerrainTypes() throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_ListOfTrackPieceTemplates(final Attributes meta)
throws SAXException;
/**
* A container element end event handling method.
*/
void end_ListOfTrackPieceTemplates() throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_ListOfLegalRoutesAcrossNode(final Attributes meta)
throws SAXException;
/**
* A container element end event handling method.
*/
void end_ListOfLegalRoutesAcrossNode() throws SAXException;
/**
* An empty element event handling method.
*/
void handle_LegalRouteAcrossNode(final Attributes meta) throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_CannotBuildOnTheseTerrainTypes(final Attributes meta)
throws SAXException;
/**
* A container element end event handling method.
*/
void end_CannotBuildOnTheseTerrainTypes() throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_TrackType(final Attributes meta) throws SAXException;
/**
* A container element end event handling method.
*/
void end_TrackType() throws SAXException;
/**
* An empty element event handling method.
*/
void handle_TerrainType(final Attributes meta) throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_Tiles(final Attributes meta) throws SAXException;
/**
* A container element end event handling method.
*/
void end_Tiles() throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_TrackPieceTemplate(final Attributes meta) throws SAXException;
/**
* A container element end event handling method.
*/
void end_TrackPieceTemplate() throws SAXException;
/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_TrackSet(final Attributes meta) throws SAXException;
/**
* A container element end event handling method.
*/
void end_TrackSet() throws SAXException;
}

CargoAndTerrainParser

Full name: jfreerails.server.parser.CargoAndTerrainParser

Documentation

/**
* The class reads XML documents according to specified DTD and translates all
* related events into CargoAndTerrainHandler events.
* <p>
* Usage sample:
*
* <pre>
* RulesParser parser = new RulesParser(...);
* parser.parse(new InputSource(&quot;...&quot;));
* </pre>
*
* <p>
* <b>Warning:</b> the class is machine generated. DO NOT MODIFY
* </p>
*
* @author Luke
*/

Source Code

/**
* The class reads XML documents according to specified DTD and translates all
* related events into CargoAndTerrainHandler events.
* <p>
* Usage sample:
*
* <pre>
* RulesParser parser = new RulesParser(...);
* parser.parse(new InputSource(&quot;...&quot;));
* </pre>
*
* <p>
* <b>Warning:</b> the class is machine generated. DO NOT MODIFY
* </p>
*
* @author Luke
*/
public class CargoAndTerrainParser implements ContentHandler {
private static final Logger logger = Logger
.getLogger(CargoAndTerrainParser.class.getName());
private java.lang.StringBuffer buffer;
private CargoAndTerrainHandler handler;
private java.util.Stack<Object[]> context;
private EntityResolver resolver;
/**
* Creates a parser instance.
*
* @param handler
* handler interface implementation (never <code>null</code>
* @param resolver
* SAX entity resolver implementation or <code>null</code>. It
* is recommended that it could be able to resolve at least the
* DTD.
*/
public CargoAndTerrainParser(final CargoAndTerrainHandler handler,
final EntityResolver resolver) {
this.handler = handler;
this.resolver = resolver;
buffer = new StringBuffer(111);
context = new java.util.Stack<Object[]>();
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void setDocumentLocator(Locator locator) {
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void startDocument() throws SAXException {
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void endDocument() throws SAXException {
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void startElement(java.lang.String ns, java.lang.String name,
java.lang.String qname, Attributes attrs) throws SAXException {
dispatch(true);
context.push(new Object[] { qname,
new org.xml.sax.helpers.AttributesImpl(attrs) });
if ("Converts".equals(name)) {
handler.handle_Converts(attrs);
} else if ("Tile".equals(name)) {
handler.start_Tile(attrs);
} else if ("Cargo".equals(name)) {
handler.handle_Cargo(attrs);
} else if ("Cargo_Types".equals(name)) {
handler.start_Cargo_Types(attrs);
} else if ("Terrain_Types".equals(name)) {
handler.start_Terrain_Types(attrs);
} else if ("Types".equals(name)) {
handler.start_Types(attrs);
} else if ("Consumes".equals(name)) {
handler.handle_Consumes(attrs);
} else if ("Produces".equals(name)) {
handler.handle_Produces(attrs);
}
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void endElement(java.lang.String ns, java.lang.String name,
java.lang.String qname) throws SAXException {
dispatch(false);
context.pop();
if ("Tile".equals(name)) {
handler.end_Tile();
} else if ("Cargo_Types".equals(name)) {
handler.end_Cargo_Types();
} else if ("Terrain_Types".equals(name)) {
handler.end_Terrain_Types();
} else if ("Types".equals(name)) {
handler.end_Types();
}
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void characters(char[] chars, int start, int len)
throws SAXException {
buffer.append(chars, start, len);
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void ignorableWhitespace(char[] chars, int start, int len)
throws SAXException {
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void processingInstruction(java.lang.String target,
java.lang.String data) throws SAXException {
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void startPrefixMapping(final java.lang.String prefix,
final java.lang.String uri) throws SAXException {
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void endPrefixMapping(final java.lang.String prefix)
throws SAXException {
}
/**
* This SAX interface method is implemented by the parser.
*
*/
public final void skippedEntity(java.lang.String name) throws SAXException {
}
private void dispatch(final boolean fireOnlyIfMixed) throws SAXException {
if (fireOnlyIfMixed && buffer.length() == 0) {
return; // skip it
}
buffer.delete(0, buffer.length());
}
/**
* The recognizer entry method taking an Inputsource.
*
* @param input
* InputSource to be parsed.
* @throws java.io.IOException
* on I/O error.
* @throws SAXException
* propagated exception thrown by a DocumentHandler.
* @throws javax.xml.parsers.ParserConfigurationException
* a parser satisfying requested configuration can not be
* created.
*
*/
public static void parse(final InputSource input,
final CargoAndTerrainHandler handler) throws SAXException,
javax.xml.parsers.ParserConfigurationException, java.io.IOException {
parse(input, new CargoAndTerrainParser(handler, null));
}
/**
* The recognizer entry method taking a URL.
*
* @param url
* URL source to be parsed.
* @throws java.io.IOException
* on I/O error.
* @throws SAXException
* propagated exception thrown by a DocumentHandler.
* @throws javax.xml.parsers.ParserConfigurationException
* a parser satisfying requested configuration can not be
* created.
*
*/
public static void parse(final java.net.URL url,
final CargoAndTerrainHandler handler) throws SAXException,
javax.xml.parsers.ParserConfigurationException, java.io.IOException {
parse(new InputSource(url.toExternalForm()), handler);
}
private static void parse(final InputSource input,
final CargoAndTerrainParser recognizer) throws SAXException,
javax.xml.parsers.ParserConfigurationException, java.io.IOException {
javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory
.newInstance();
factory.setValidating(true); // the code was generated according DTD
factory.setNamespaceAware(true); // the code was generated according
// DTD
XMLReader parser = factory.newSAXParser().getXMLReader();
parser.setContentHandler(recognizer);
parser.setErrorHandler(recognizer.getDefaultErrorHandler());
if (recognizer.resolver != null) {
parser.setEntityResolver(recognizer.resolver);
}
parser.parse(input);
}
/**
* Creates default error handler used by this parser.
*
* @return org.xml.sax.ErrorHandler implementation
*
*/
protected ErrorHandler getDefaultErrorHandler() {
return new ErrorHandler() {
public void error(SAXParseException ex) throws SAXException {
if (context.isEmpty()) {
logger.severe("Missing DOCTYPE.");
}
throw ex;
}
public void fatalError(SAXParseException ex) throws SAXException {
throw ex;
}
public void warning(SAXParseException ex) throws SAXException {
// ignore
}
};
}
}

CargoAndTerrainHandlerImpl

Full name: jfreerails.server.parser.CargoAndTerrainHandlerImpl

Documentation

/**
* Processes CargoAndTerrainHandler events and adds terrain and cargo types to
* the world object.
*
* @see CargoAndTerrainHandler
* @see CargoAndTerrainParser
* @author Luke
* @version generated by NetBeans XML module
*/

Source Code

/**
* Processes CargoAndTerrainHandler events and adds terrain and cargo types to
* the world object.
*
* @see CargoAndTerrainHandler
* @see CargoAndTerrainParser
* @author Luke
* @version generated by NetBeans XML module
*/
public class CargoAndTerrainHandlerImpl implements CargoAndTerrainHandler {
private final World world;
HashMap<String, Integer> cargoName2cargoTypeNumber = new HashMap<String, Integer>();
HashSet<Integer> rgbValuesAlreadyUsed = new HashSet<Integer>();
// Parsing variables for Tile
String tileID;
TerrainType.Category tileCategory;
int tileRGB;
int tileROW;
int tileBuildCost;
ArrayList<Consumption> typeConsumes = new ArrayList<Consumption>();
ArrayList<Production> typeProduces = new ArrayList<Production>();
ArrayList<Conversion> typeConverts = new ArrayList<Conversion>();
public CargoAndTerrainHandlerImpl(World w) {
world = w;
}
public void handle_Converts(final Attributes meta) throws SAXException {
String inputCargo = meta.getValue("input");
String outputCargo = meta.getValue("output");
int input = string2CargoID(inputCargo);
int output = string2CargoID(outputCargo);
Conversion conversion = new Conversion(input, output);
typeConverts.add(conversion);
}
public void start_Tile(final Attributes meta) throws SAXException {
typeConsumes.clear();
typeProduces.clear();
typeConverts.clear();
tileID = meta.getValue("id");
tileCategory = TerrainType.Category.valueOf(meta.getValue("Category"));
String rgbString = meta.getValue("rgb");
tileRGB = string2RGBValue(rgbString);
String buildCostString = meta.getValue("build_cost");
if (null != buildCostString) {
tileBuildCost = Integer.parseInt(buildCostString);
} else {
tileBuildCost = -1;
}
// Check if another type is already using this rgb value..
Integer rgbInteger = new Integer(tileRGB);
if (rgbValuesAlreadyUsed.contains(rgbInteger)) {
throw new SAXException(tileID + " can't using rgb value "
+ rgbString
+ " because it is being used by another tile type!");
}
rgbValuesAlreadyUsed.add(rgbInteger);
tileROW = Integer.parseInt(meta.getValue("right-of-way"));
}
public void end_Tile() throws SAXException {
Consumption[] consumes = new Consumption[typeConsumes.size()];
for (int i = 0; i < typeConsumes.size(); i++) {
consumes[i] = typeConsumes.get(i);
}
Production[] produces = new Production[typeProduces.size()];
for (int i = 0; i < typeProduces.size(); i++) {
produces[i] = typeProduces.get(i);
}
Conversion[] converts = new Conversion[typeConverts.size()];
for (int i = 0; i < typeConverts.size(); i++) {
converts[i] = typeConverts.get(i);
}
TileTypeImpl tileType = new TileTypeImpl(tileRGB, tileCategory, tileID,
tileROW, produces, consumes, converts, tileBuildCost);
world.add(SKEY.TERRAIN_TYPES, tileType);
}
public void handle_Cargo(final Attributes meta) throws SAXException {
String cargoID = meta.getValue("id");
String cargoCategory = meta.getValue("Category");
int unitWeight = Integer.parseInt(meta.getValue("unitWeight"));
CargoType cargoType = new CargoType(unitWeight, cargoID, Categories
.getCategory(cargoCategory));
int cargoNumber = world.size(SKEY.CARGO_TYPES);
cargoName2cargoTypeNumber.put(cargoID, new Integer(cargoNumber));
world.add(SKEY.CARGO_TYPES, cargoType);
}
public void start_Cargo_Types(final Attributes meta) throws SAXException {
// no need to do anything here.
}
public void end_Cargo_Types() throws SAXException {
// no need to do anything here.
}
public void start_Terrain_Types(final Attributes meta) throws SAXException {
// no need to do anything here.
}
public void end_Terrain_Types() throws SAXException {
// no need to do anything here.
}
public void start_Types(final Attributes meta) throws SAXException {
// no need to do anything here.
}
public void end_Types() throws SAXException {
// no need to do anything here.
}
public void handle_Consumes(final Attributes meta) throws SAXException {
int cargoConsumed = string2CargoID(meta.getValue("Cargo"));
String prerequisiteString = meta.getValue("Prerequisite");
// "Prerequisite" is an optional attribute, so may be null.
int prerequisiteForConsumption = (null == prerequisiteString ? 1
: Integer.parseInt(prerequisiteString));
Consumption consumption = new Consumption(cargoConsumed,
prerequisiteForConsumption);
typeConsumes.add(consumption);
}
public void handle_Produces(final Attributes meta) throws SAXException {
int cargoProduced = string2CargoID(meta.getValue("Cargo"));
int rateOfProduction = Integer.parseInt(meta.getValue("Rate"));
Production production = new Production(cargoProduced, rateOfProduction);
typeProduces.add(production);
}
private int string2RGBValue(String temp_number) {
int rgb = Integer.parseInt(temp_number, 16);
/*
* We need to change the format of the rgb value to the same one as used
* by the the BufferedImage that stores the map. See
* jfreerails.common.Map
*/
rgb = new java.awt.Color(rgb).getRGB();
return rgb;
}
/** Returns the index number of the cargo with the specified name. */
private int string2CargoID(String cargoName) throws SAXException {
if (cargoName2cargoTypeNumber.containsKey(cargoName)) {
Integer integer = cargoName2cargoTypeNumber.get(cargoName);
return integer.intValue();
}
throw new SAXException("Unknown cargo type: " + cargoName);
}
}

Track_TilesParser

Full name: jfreerails.server.parser.Track_TilesParser

Documentation

/**
* The class reads XML documents according to specified DTD and translates all
* related events into Track_TilesHandler events.
* <p>
* Usage sample:
*
* <pre>
* Track_TilesParser parser = new Track_TilesParser(...);
* parser.parse(new InputSource(&quot;...&quot;));
* </pre>
*
* Date: 21 January 2002 18:00
*
* @author lindsal
* @version generated by FFJ XML module
*/

Source Code

/**
* The class reads XML documents according to specified DTD and translates all
* related events into Track_TilesHandler events.
* <p>
* Usage sample:
*
* <pre>
* Track_TilesParser parser = new Track_TilesParser(...);
* parser.parse(new InputSource(&quot;...&quot;));
* </pre>
*
* Date: 21 January 2002 18:00
*
* @author lindsal
* @version generated by FFJ XML module
*/
final public class Track_TilesParser implements org.xml.sax.ContentHandler {
private static final Logger logger = Logger
.getLogger(Track_TilesParser.class.getName());
private java.lang.StringBuffer buffer;
private Track_TilesHandler handler;
private java.util.Stack<Object[]> context;
public Track_TilesParser(final Track_TilesHandler handler) {
this.handler = handler;
buffer = new StringBuffer(111);
context = new java.util.Stack<Object[]>();
}
public void setDocumentLocator(org.xml.sax.Locator locator) {
}
public void startDocument() throws SAXException {
}
public void endDocument() throws SAXException {
}
public void startElement(java.lang.String ns, java.lang.String name,
java.lang.String qname, org.xml.sax.Attributes attrs)
throws SAXException {
dispatch(true);
context.push(new Object[] { qname,
new org.xml.sax.helpers.AttributesImpl(attrs) });
if ("CanOnlyBuildOnTheseTerrainTypes".equals(qname)) {
handler.start_CanOnlyBuildOnTheseTerrainTypes(attrs);
} else if ("ListOfTrackPieceTemplates".equals(qname)) {
handler.start_ListOfTrackPieceTemplates(attrs);
} else if ("ListOfLegalRoutesAcrossNode".equals(qname)) {
handler.start_ListOfLegalRoutesAcrossNode(attrs);
} else if ("LegalRouteAcrossNode".equals(qname)) {
handler.handle_LegalRouteAcrossNode(attrs);
} else if ("CannotBuildOnTheseTerrainTypes".equals(qname)) {
handler.start_CannotBuildOnTheseTerrainTypes(attrs);
} else if ("TrackType".equals(qname)) {
handler.start_TrackType(attrs);
} else if ("TerrainType".equals(qname)) {
handler.handle_TerrainType(attrs);
} else if ("Tiles".equals(qname)) {
handler.start_Tiles(attrs);
} else if ("TrackPieceTemplate".equals(qname)) {
handler.start_TrackPieceTemplate(attrs);
} else if ("TrackSet".equals(qname)) {
handler.start_TrackSet(attrs);
}
}
public void endElement(java.lang.String ns, java.lang.String name,
java.lang.String qname) throws SAXException {
dispatch(false);
context.pop();
if ("CanOnlyBuildOnTheseTerrainTypes".equals(qname)) {
handler.end_CanOnlyBuildOnTheseTerrainTypes();
} else if ("ListOfTrackPieceTemplates".equals(qname)) {
handler.end_ListOfTrackPieceTemplates();
} else if ("ListOfLegalRoutesAcrossNode".equals(qname)) {
handler.end_ListOfLegalRoutesAcrossNode();
} else if ("CannotBuildOnTheseTerrainTypes".equals(qname)) {
handler.end_CannotBuildOnTheseTerrainTypes();
} else if ("TrackType".equals(qname)) {
handler.end_TrackType();
} else if ("Tiles".equals(qname)) {
handler.end_Tiles();
} else if ("TrackPieceTemplate".equals(qname)) {
handler.end_TrackPieceTemplate();
} else if ("TrackSet".equals(qname)) {
handler.end_TrackSet();
}
}
public void characters(char[] chars, int start, int len)
throws SAXException {
buffer.append(chars, start, len);
}
public void ignorableWhitespace(char[] chars, int start, int len)
throws SAXException {
}
public void processingInstruction(java.lang.String target,
java.lang.String data) throws SAXException {
}
public void startPrefixMapping(final java.lang.String prefix,
final java.lang.String uri) throws SAXException {
}
public void endPrefixMapping(final java.lang.String prefix)
throws SAXException {
}
public void skippedEntity(java.lang.String name) throws SAXException {
}
private void dispatch(final boolean fireOnlyIfMixed) throws SAXException {
if (fireOnlyIfMixed && buffer.length() == 0) {
return; // skip it
}
buffer.delete(0, buffer.length());
}
/**
* The recognizer entry method taking an Inputsource.
*
* @param input
* InputSource to be parsed.
* @throws java.io.IOException
* on I/O error.
* @throws SAXException
* propagated exception thrown by a DocumentHandler.
* @throws javax.xml.parsers.ParserConfigurationException
* a parser satisfying requested configuration can not be
* created.
*/
public static void parse(final InputSource input,
final Track_TilesHandler handler) throws SAXException,
ParserConfigurationException, IOException {
parse(input, new Track_TilesParser(handler));
}
/**
* The recognizer entry method taking a URL.
*
* @param url
* URL source to be parsed.
* @throws java.io.IOException
* on I/O error.
* @throws SAXException
* propagated exception thrown by a DocumentHandler.
* @throws javax.xml.parsers.ParserConfigurationException
* a parser satisfying requested configuration can not be
* created.
*/
public static void parse(final java.net.URL url,
final Track_TilesHandler handler) throws SAXException,
ParserConfigurationException, IOException {
parse(new InputSource(url.toExternalForm()), handler);
}
private static void parse(final InputSource input,
final Track_TilesParser recognizer) throws SAXException,
ParserConfigurationException, IOException {
javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory
.newInstance();
factory.setValidating(true); // the code was generated according DTD
factory.setNamespaceAware(false); // the code was generated according
// DTD
org.xml.sax.XMLReader parser = factory.newSAXParser().getXMLReader();
parser.setContentHandler(recognizer);
parser.setErrorHandler(recognizer.getDefaultErrorHandler());
parser.parse(input);
}
private org.xml.sax.ErrorHandler getDefaultErrorHandler() {
return new org.xml.sax.ErrorHandler() {
public void error(org.xml.sax.SAXParseException ex)
throws SAXException {
if (context.isEmpty()) {
logger.severe("Missing DOCTYPE.");
}
throw ex;
}
public void fatalError(org.xml.sax.SAXParseException ex)
throws SAXException {
throw ex;
}
public void warning(org.xml.sax.SAXParseException ex)
throws SAXException {
// ignore
}
};
}
}

SynchronizedQueue

Full name: jfreerails.network.SynchronizedQueue

Documentation

/**
* Intended to let objects be safely passed between threads.
*
* @author Luke
*
*/

Source Code

/**
* Intended to let objects be safely passed between threads.
*
* @author Luke
*
*/
public class SynchronizedQueue {
private final LinkedList<FreerailsSerializable> queue = new LinkedList<FreerailsSerializable>();
public synchronized void write(FreerailsSerializable f) {
queue.add(f);
}
public synchronized FreerailsSerializable[] read() {
int length = queue.size();
FreerailsSerializable[] read = new FreerailsSerializable[length];
for (int i = 0; i < length; i++) {
read[i] = queue.removeFirst();
}
return read;
}
public synchronized int size() {
return queue.size();
}
public synchronized FreerailsSerializable getFirst() {
return queue.removeFirst();
}
}

Connection2Server

Full name: jfreerails.network.Connection2Server

Documentation

/**
* Defines the methods a client can use to send messages to the server.
*
* @author Luke
*
*/

Source Code

/**
* Defines the methods a client can use to send messages to the server.
*
* @author Luke
*
*/
public interface Connection2Server {
/** Returns true if this connection is open. */
boolean isOpen();
/**
* Returns an array containing all the objects read from the server since
* the last time this method or waitForObjectFromServer() was called, if no
* objects have been received, it returns an empty array rather than
* blocking.
*/
FreerailsSerializable[] readFromServer() throws IOException;
/**
* Returns the next object read from the server, blocking if non is
* available.
*/
FreerailsSerializable waitForObjectFromServer() throws IOException,
InterruptedException;
/** Sends the specified object to the server. */
void writeToServer(FreerailsSerializable object) throws IOException;
/**
* Disconnect from the server. When this method returns, calling isOpen() on
* this object returns false <b>and</b> calling isOpen() on the
* corresponding Connection2Client held by the server also returns false.
*
* @throws IOException
*/
void disconnect() throws IOException;
/** Flush the underlying stream. */
void flush() throws IOException;
String getServerDetails();
}

EchoGameServer

Full name: jfreerails.network.EchoGameServer

Documentation

/**
* Implementation of GameServer that simply echoes whatever clients send it.
*
* @author Luke
*
*/

Source Code

/**
* Implementation of GameServer that simply echoes whatever clients send it.
*
* @author Luke
*
*/
public class EchoGameServer implements GameServer, Runnable {
private static final Logger logger = Logger.getLogger(EchoGameServer.class
.getName());
private final Vector<Connection2Client> connections = new Vector<Connection2Client>();
private final SynchronizedFlag status = new SynchronizedFlag(false);
private final LinkedList<FreerailsSerializable> messages2send = new LinkedList<FreerailsSerializable>();
private EchoGameServer() {
}
/**
* Creates an EchoGameServer, starts it in a new Thread, and waits for its
* status to change to isOpen before returning.
*/
public static EchoGameServer startServer() {
EchoGameServer server = new EchoGameServer();
Thread t = new Thread(server);
t.start();
try {
/* Wait for the server to start before returning. */
synchronized (server.status) {
server.status.wait();
}
return server;
} catch (InterruptedException e) {
e.printStackTrace();
throw new IllegalStateException();
}
}
public synchronized void addConnection(Connection2Client connection) {
if (null == connection) {
throw new NullPointerException();
}
if (!status.isOpen()) {
throw new IllegalArgumentException();
}
connections.add(connection);
}
public synchronized int countOpenConnections() {
Iterator<Connection2Client> it = connections.iterator();
while (it.hasNext()) {
Connection2Client connection = it.next();
if (!connection.isOpen()) {
it.remove();
}
}
return connections.size();
}
public synchronized void stop() {
status.close();
for (int i = 0; i < connections.size(); i++) {
AbstractInetConnection connection = (AbstractInetConnection) connections
.get(i);
if (connection.isOpen()) {
try {
connection.setTimeOut(0);
connection.disconnect();
} catch (Exception e) {
// Do nothing.
}
}
}
}
public void run() {
status.open();
while (status.isOpen()) {
update();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// do nothing.
}
}
}
synchronized void sendMessage(FreerailsSerializable m) {
/* Send messages. */
for (int i = 0; i < connections.size(); i++) {
Connection2Client connection = connections.get(i);
try {
connection.writeToClient(m);
connection.flush();
logger.fine("Sent ok: " + m);
} catch (IOException e) {
try {
if (connection.isOpen()) {
connection.disconnect();
}
} catch (IOException e1) {
// hope this doesn't happen.
e1.printStackTrace();
}
}
}
}
public void update() {
synchronized (this) {
/* Read messages. */
for (int i = 0; i < connections.size(); i++) {
Connection2Client connection = connections.get(i);
try {
FreerailsSerializable[] messages = connection
.readFromClient();
for (int j = 0; j < messages.length; j++) {
messages2send.add(messages[j]);
}
} catch (IOException e) {
try {
if (connection.isOpen()) {
connection.disconnect();
}
} catch (IOException e1) {
//
e1.printStackTrace();
}
}
}
/* Send messages. */
Iterator<FreerailsSerializable> messagesIterator = messages2send
.iterator();
while (messagesIterator.hasNext()) {
FreerailsSerializable message = messagesIterator.next();
sendMessage(message);
}
}
}
}

AbstractInetConnection

Full name: jfreerails.network.AbstractInetConnection

Documentation

/**
* This class has the code that is shared by the client and server versions of
* InetConnection.
*
* @author Luke
*/

Source Code

/**
* This class has the code that is shared by the client and server versions of
* InetConnection.
*
* @author Luke
*/
public abstract class AbstractInetConnection implements Runnable {
private static final Logger logger = Logger
.getLogger(AbstractInetConnection.class.getName());
private final SynchronizedQueue inbound = new SynchronizedQueue();
private final InetConnection inetConnection;
private final SynchronizedFlag readerThreadStatus = new SynchronizedFlag(
false);
private final SynchronizedFlag status = new SynchronizedFlag(true);
private int timeout = 1000 * 5; // 5 seconds.
public AbstractInetConnection(Socket s) throws IOException {
inetConnection = new InetConnection(s);
open();
}
public AbstractInetConnection(String ip, int port) throws IOException {
inetConnection = new InetConnection(ip, port);
open();
}
public void disconnect() throws IOException {
logger.fine(this + "Initiating shutdown..");
shutdownOutput();
long waitUntil = System.currentTimeMillis() + timeout;
synchronized (readerThreadStatus) {
while (readerThreadStatus.isOpen()) {
long currentTime = System.currentTimeMillis();
if (currentTime >= waitUntil) {
shutDownInput();
throw new IOException(
"Time-out while trying to disconnect.");
}
try {
readerThreadStatus.wait(timeout);
} catch (InterruptedException e) {
// do nothing.
}
}
}
logger.fine(this + "Finished shutdown!! --status="
+ String.valueOf(status.isOpen()));
}
public void flush() throws IOException {
inetConnection.flush();
}
public synchronized boolean isOpen() {
return status.isOpen();
}
public void run() {
try {
while (true) {
FreerailsSerializable fs = inetConnection.receive();
synchronized (inbound) {
inbound.write(fs);
inbound.notifyAll();
}
}
} catch (EOFException e) {
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
logger.fine(this + "Reciprocating shutdown..");
shutDownInput();
readerThreadStatus.close();
}
private synchronized void open() throws IOException {
Thread t = new Thread(this);
t.setName(getThreadName());
inetConnection.open();
t.start();
readerThreadStatus.open();
}
private synchronized void shutDownInput() {
try {
inetConnection.shutdownInput();
logger.fine(this + "Shut down input.");
if (status.isOpen()) {
shutdownOutput();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
private synchronized void shutdownOutput() throws IOException {
if (!status.isOpen()) {
throw new IllegalStateException();
}
status.close();
inetConnection.shutdownOutput();
logger.fine(this + "Shut down output.");
}
abstract String getThreadName();
FreerailsSerializable[] read() throws IOException {
if (status.isOpen()) {
return inbound.read();
}
throw new IOException();
}
void send(FreerailsSerializable object) throws IOException {
inetConnection.send(object);
}
void setTimeOut(int i) {
timeout = i;
}
FreerailsSerializable waitForObject() throws InterruptedException,
IOException {
if (status.isOpen()) {
synchronized (inbound) {
if (inbound.size() > 0) {
return inbound.getFirst();
}
inbound.wait();
if (inbound.size() > 0) {
return inbound.getFirst();
}
throw new IllegalStateException();
}
}
throw new IOException("The connection is close.");
}
}

InetConnection2Client

Full name: jfreerails.network.InetConnection2Client

Documentation

/**
* Lets the server send messages to a client over the Internet.
*
* @author Luke
*
*/

Source Code

/**
* Lets the server send messages to a client over the Internet.
*
* @author Luke
*
*/
public class InetConnection2Client extends AbstractInetConnection implements
Connection2Client {
public InetConnection2Client(Socket s) throws IOException {
super(s);
}
public FreerailsSerializable[] readFromClient() throws IOException {
return read();
}
public FreerailsSerializable waitForObjectFromClient() throws IOException,
InterruptedException {
return waitForObject();
}
public void writeToClient(FreerailsSerializable object) throws IOException {
send(object);
}
@Override
String getThreadName() {
return "InetConnection2Client";
}
}

InetConnection2Server

Full name: jfreerails.network.InetConnection2Server

Documentation

/**
* Lets a client send messages to the server over the Internet.
*
* @author Luke
*
*/

Source Code

/**
* Lets a client send messages to the server over the Internet.
*
* @author Luke
*
*/
public class InetConnection2Server extends AbstractInetConnection implements
Connection2Server {
final String serverDetails;
public InetConnection2Server(String ip, int port) throws IOException {
super(ip, port);
serverDetails = "server at " + ip + ":" + port;
}
public FreerailsSerializable[] readFromServer() throws IOException {
return read();
}
public FreerailsSerializable waitForObjectFromServer() throws IOException,
InterruptedException {
return waitForObject();
}
public void writeToServer(FreerailsSerializable object) throws IOException {
send(object);
}
@Override
String getThreadName() {
return "InetConnection2Server";
}
public String getServerDetails() {
return serverDetails;
}
}

SynchronizedFlag

Full name: jfreerails.network.SynchronizedFlag

Documentation

/**
* Synchronized flag - used to tell threads whether they should keep going.
* Note, thought about using volatile keyword but wasn't sure if it is
* implemented on all JVMs
*
* @author Luke
*/

Source Code

/**
* Synchronized flag - used to tell threads whether they should keep going.
* Note, thought about using volatile keyword but wasn't sure if it is
* implemented on all JVMs
*
* @author Luke
*/
public class SynchronizedFlag {
public SynchronizedFlag(boolean b) {
this.isOpen = b;
}
private boolean isOpen = true;
public synchronized boolean isOpen() {
return isOpen;
}
public synchronized void close() {
this.isOpen = false;
notifyAll();
}
public synchronized void open() {
this.isOpen = true;
notifyAll();
}
}

InetConnection

Full name: jfreerails.network.InetConnection

Documentation

/**
* Provides methods send objects over the Internet, and connect and disconnect
* gracefully.
*
* @author Luke
*
*/

Source Code

/**
* Provides methods send objects over the Internet, and connect and disconnect
* gracefully.
*
* @author Luke
*
*/
public class InetConnection {
private final Socket socket;
// Note compression commented out since it was causing junit tests to fail.
// Not
// sure why. LL
// private DeflaterOutputStream deflaterOutputStream;
// private InflaterInputStream inflaterInputStream;
private ObjectOutputStream objectOutputStream;
private ObjectInputStream objectInputStream;
private static final String CONNECTION_OPEN = "CONNECTION_OPEN";
InetConnection(Socket acceptedConnection) throws IOException {
socket = acceptedConnection;
}
InetConnection(String s, int port) throws IOException {
this(new Socket(s, port));
}
/**
* Sets up the input and output streams, then sends the String
* "CONNECTION_OPEN" and attempts to read the same String back.
*/
synchronized void open() throws IOException {
OutputStream outputStream = socket.getOutputStream();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
outputStream);
// deflaterOutputStream = new DeflaterOutputStream(outputStream);
// objectOutputStream = new ObjectOutputStream(deflaterOutputStream);
objectOutputStream = new ObjectOutputStream(bufferedOutputStream);
objectOutputStream.writeObject(CONNECTION_OPEN);
objectOutputStream.flush();
InputStream inputStream = socket.getInputStream();
// inflaterInputStream = new InflaterInputStream(inputStream);
// objectInputStream = new ObjectInputStream(inflaterInputStream);
objectInputStream = new ObjectInputStream(inputStream);
try {
String s = (String) objectInputStream.readObject();
if (!s.equals(CONNECTION_OPEN)) {
throw new IllegalStateException(s);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IOException(e.getMessage());
}
}
synchronized void send(FreerailsSerializable object) throws IOException {
objectOutputStream.writeObject(object);
flush();
}
FreerailsSerializable receive() throws IOException, ClassNotFoundException {
Object object = objectInputStream.readObject();
return (FreerailsSerializable) object;
}
synchronized boolean isOpen() {
boolean isClosed = socket.isClosed();
return !isClosed;
}
synchronized void flush() throws IOException {
objectOutputStream.flush();
// deflaterOutputStream.flush();
// deflaterOutputStream.finish();
// deflaterOutputStream.flush();
}
synchronized void shutdownOutput() throws IOException {
socket.shutdownOutput();
if (socket.isInputShutdown() && socket.isOutputShutdown()) {
socket.close();
}
}
synchronized void shutdownInput() throws IOException {
socket.shutdownInput();
if (socket.isInputShutdown() && socket.isOutputShutdown()) {
socket.close();
}
}
}

LocalConnection

Full name: jfreerails.network.LocalConnection

Documentation

/**
* A connection between the a client and server in the same JVM.
*
* @author Luke
*
*/

Source Code

/**
* A connection between the a client and server in the same JVM.
*
* @author Luke
*
*/
public class LocalConnection implements Connection2Client, Connection2Server {
public static final String SERVER_IN_SAME_JVM = "server in same JVM";
private final SynchronizedQueue fromServer = new SynchronizedQueue();
private final SynchronizedQueue fromClient = new SynchronizedQueue();
private final SynchronizedFlag status = new SynchronizedFlag(true);
public LocalConnection() {
}
public FreerailsSerializable[] readFromClient() throws IOException {
if (status.isOpen()) {
return fromClient.read();
}
throw new IOException();
}
public FreerailsSerializable waitForObjectFromClient() throws IOException,
InterruptedException {
synchronized (fromClient) {
if (fromClient.size() == 0) {
fromClient.wait();
}
if (status.isOpen()) {
return fromClient.getFirst();
}
throw new IOException();
}
}
public void writeToClient(FreerailsSerializable object) throws IOException {
if (status.isOpen()) {
synchronized (fromServer) {
fromServer.write(object);
fromServer.notifyAll();
}
} else {
throw new IOException();
}
}
public FreerailsSerializable[] readFromServer() throws IOException {
if (status.isOpen()) {
return fromServer.read();
}
throw new IOException();
}
public FreerailsSerializable waitForObjectFromServer() throws IOException,
InterruptedException {
if (status.isOpen()) {
synchronized (fromServer) {
if (fromServer.size() == 0) {
fromServer.wait();
}
return fromServer.getFirst();
}
}
throw new IOException();
}
public void writeToServer(FreerailsSerializable object) throws IOException {
if (status.isOpen()) {
synchronized (fromClient) {
fromClient.write(object);
fromClient.notifyAll();
}
} else {
throw new IOException();
}
}
public boolean isOpen() {
return status.isOpen();
}
public void flush() {
// No need to do anything.
}
public synchronized void disconnect() {
status.close();
}
public String getServerDetails() {
return SERVER_IN_SAME_JVM;
}
}

GameServer

Full name: jfreerails.network.GameServer

Documentation

/**
* Defines a server that can accept connections to clients.
*
* @author Luke
*
*/

Source Code

/**
* Defines a server that can accept connections to clients.
*
* @author Luke
*
*/
public interface GameServer extends GameModel {
void addConnection(Connection2Client connection);
int countOpenConnections();
void stop();
}

InetConnectionAccepter

Full name: jfreerails.network.InetConnectionAccepter

Documentation

/**
* When this class is run in a thread it accepts new connections to its Server
* Socket and adds them to the NewGameServer that was passed to its constructor.
*
* @author Luke
*/

Source Code

/**
* When this class is run in a thread it accepts new connections to its Server
* Socket and adds them to the NewGameServer that was passed to its constructor.
*
* @author Luke
*/
public class InetConnectionAccepter implements Runnable {
private static final Logger logger = Logger
.getLogger(InetConnectionAccepter.class.getName());
public static void main(String[] args) {
try {
GameServer echoGameServer = EchoGameServer.startServer();
InetConnectionAccepter accepter = new InetConnectionAccepter(6666,
echoGameServer);
Thread t = new Thread(accepter);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
private final GameServer gameServer;
private final SynchronizedFlag keepRunning = new SynchronizedFlag(true);
private final ServerSocket serverSocket;
public InetConnectionAccepter(int port, GameServer gameServer)
throws IOException {
if (null == gameServer)
throw new NullPointerException();
this.gameServer = gameServer;
serverSocket = new ServerSocket(port);
}
public void run() {
Thread.currentThread().setName(
"InetConnectionAccepter, port " + serverSocket.getLocalPort());
try {
logger.fine("Accepting connections on port "
+ serverSocket.getLocalPort());
while (isKeepRunning()) {
Socket socket = serverSocket.accept();
logger.fine("Incoming connection from "
+ socket.getRemoteSocketAddress());
synchronized (this) {
synchronized (gameServer) {
InetConnection2Client connection = new InetConnection2Client(
socket);
gameServer.addConnection(connection);
}
}
}
} catch (IOException e) {
try {
stop();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
public synchronized void stop() throws IOException {
this.keepRunning.close();
serverSocket.close();
// Commented out since it causes exceptions to be thrown, fixes bug
// 979831
// gameServer.stop();
}
private boolean isKeepRunning() {
return keepRunning.isOpen();
}
public int getLocalPort() {
return serverSocket.getLocalPort();
}
}

Connection2Client

Full name: jfreerails.network.Connection2Client

Documentation

/**
* Defines the methods the server can use to send messages to the client.
*
* @author Luke
*
*/

Source Code

/**
* Defines the methods the server can use to send messages to the client.
*
* @author Luke
*
*/
public interface Connection2Client {
/** Returns true if this connection is open. */
boolean isOpen();
/**
* Returns an array containing all the objects read from the client since
* the last time this method or waitForObjectFromClient() was called, if no
* objects have been received, it returns an empty array rather than
* blocking.
*/
FreerailsSerializable[] readFromClient() throws IOException;
/**
* Returns the next object read from the client, blocking if non is
* available.
*/
FreerailsSerializable waitForObjectFromClient() throws IOException,
InterruptedException;
/** Sends the specified object to the client. */
void writeToClient(FreerailsSerializable object) throws IOException;
/** Flush the underlying stream. */
void flush() throws IOException;
/**
* Disconnect from the client. When this method returns, calling isOpen() on
* this object returns false <b>and</b> calling isOpen() on the
* corresponding Connection2Server held by the client also returns false.
*
* @throws IOException
*/
void disconnect() throws IOException;
}

NewGameMessage2Server

Full name: jfreerails.network.specifics.NewGameMessage2Server

Documentation

/**
* Request to start a game on a new map.
*
* @author Luke
*
*/

Source Code

/**
* Request to start a game on a new map.
*
* @author Luke
*
*/
public class NewGameMessage2Server implements Message2Server {
private static final long serialVersionUID = 3256723961743422513L;
private final int id;
private final String mapName;
public NewGameMessage2Server(int id, String s) {
this.id = id;
this.mapName = s;
}
public int getID() {
return id;
}
public MessageStatus execute(ServerControlInterface server) {
try {
server.newGame(mapName);
return new MessageStatus(id, true);
} catch (Exception e) {
return new MessageStatus(id, false, e.getMessage());
}
}
/**
* TODO This would be better implemented in a config file, or better still
* dynamically determined by scanning the directory.
*/
public static String[] getMapNames() {
return new String[] { "South America", "Small South America" };
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof NewGameMessage2Server))
return false;
final NewGameMessage2Server newGameMessage2Server = (NewGameMessage2Server) o;
if (id != newGameMessage2Server.id)
return false;
if (!mapName.equals(newGameMessage2Server.mapName))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + mapName.hashCode();
return result;
}
}

MoveReceiver

Full name: jfreerails.network.specifics.MoveReceiver

Documentation

/**
* Accepts a Move without the caller knowing where its going. TODO replace with
* MoveExecutor where the moves are expected to be executed.
*
* @author Luke
*/

Source Code

/**
* Accepts a Move without the caller knowing where its going. TODO replace with
* MoveExecutor where the moves are expected to be executed.
*
* @author Luke
*/
public interface MoveReceiver {
void processMove(Move move);
}

Methods

MoveChainFork

Full name: jfreerails.network.specifics.MoveChainFork

Documentation

/**
*
* A central point at which a client may register to receive moves which have
* been committed.
*
* @author Luke
* @author rob
*/

Source Code

/**
*
* A central point at which a client may register to receive moves which have
* been committed.
*
* @author Luke
* @author rob
*/
final public class MoveChainFork implements MoveReceiver {
private final ArrayList<MoveReceiver> moveReceivers = new ArrayList<MoveReceiver>();
private final ArrayList<MoveReceiver> splitMoveReceivers = new ArrayList<MoveReceiver>();
private final ArrayList<WorldListListener> listListeners = new ArrayList<WorldListListener>();
private final ArrayList<WorldMapListener> mapListeners = new ArrayList<WorldMapListener>();
private long lastTickTime = System.currentTimeMillis();
public long getLastTickTime() {
return lastTickTime;
}
public MoveChainFork() {
// do nothing
}
public void addMapListener(WorldMapListener l) {
mapListeners.add(l);
}
public void removeMapListener(WorldMapListener l) {
mapListeners.remove(l);
}
public void removeCompleteMoveReceiver(MoveReceiver moveReceiver) {
if (null == moveReceiver) {
throw new NullPointerException();
}
moveReceivers.remove(moveReceiver);
}
public void addCompleteMoveReceiver(MoveReceiver moveReceiver) {
if (null == moveReceiver) {
throw new NullPointerException();
}
moveReceivers.add(moveReceiver);
}
public void addSplitMoveReceiver(MoveReceiver moveReceiver) {
if (null == moveReceiver) {
throw new NullPointerException();
}
splitMoveReceivers.add(moveReceiver);
}
public void addListListener(WorldListListener listener) {
if (null == listener) {
throw new NullPointerException();
}
listListeners.add(listener);
}
public void processMove(Move move) {
for (int i = 0; i < moveReceivers.size(); i++) {
MoveReceiver m = moveReceivers.get(i);
m.processMove(move);
}
splitMove(move);
}
private void splitMove(Move move) {
if (move instanceof UndoMove) {
UndoMove undoneMove = (UndoMove) move;
move = undoneMove.getUndoneMove();
}
if (move instanceof CompositeMove) {
ImList<Move> moves = ((CompositeMove) move).getMoves();
for (int i = 0; i < moves.size(); i++) {
splitMove(moves.get(i));
}
} else {
for (int i = 0; i < splitMoveReceivers.size(); i++) {
MoveReceiver m = splitMoveReceivers.get(i);
m.processMove(move);
}
if (move instanceof AddItemToListMove) {
AddItemToListMove mm = (AddItemToListMove) move;
sendItemAdded(mm.getKey(), mm.getIndex(), mm.getPrincipal());
} else if (move instanceof ChangeItemInListMove) {
ChangeItemInListMove mm = (ChangeItemInListMove) move;
sendListUpdated(mm.getKey(), mm.getIndex(), mm.getPrincipal());
} else if (move instanceof RemoveItemFromListMove) {
RemoveItemFromListMove mm = (RemoveItemFromListMove) move;
sendItemRemoved(mm.getKey(), mm.getIndex(), mm.getPrincipal());
} else if (move instanceof MapUpdateMove) {
Rectangle r = ((MapUpdateMove) move).getUpdatedTiles();
sendMapUpdated(r);
} else if (move instanceof TimeTickMove) {
long currentTime = System.currentTimeMillis();
lastTickTime = currentTime;
}
}
}
private void sendMapUpdated(Rectangle r) {
for (int i = 0; i < mapListeners.size(); i++) {
WorldMapListener l = mapListeners.get(i);
l.tilesChanged(r);
}
}
private void sendItemAdded(KEY key, int index, FreerailsPrincipal p) {
for (int i = 0; i < listListeners.size(); i++) {
WorldListListener l = listListeners.get(i);
l.itemAdded(key, index, p);
}
}
private void sendItemRemoved(KEY key, int index, FreerailsPrincipal p) {
for (int i = 0; i < listListeners.size(); i++) {
WorldListListener l = listListeners.get(i);
l.itemRemoved(key, index, p);
}
}
private void sendListUpdated(KEY key, int index, FreerailsPrincipal p) {
for (int i = 0; i < listListeners.size(); i++) {
WorldListListener l = listListeners.get(i);
l.listUpdated(key, index, p);
}
}
}

LogOnResponse

Full name: jfreerails.network.specifics.LogOnResponse

Documentation

/**
* Stores the result of a request to log onto the server.
*
* @author Luke
*
*/

Source Code

/**
* Stores the result of a request to log onto the server.
*
* @author Luke
*
*/
public class LogOnResponse implements FreerailsSerializable {
private static final long serialVersionUID = 3690479099844311344L;
private final boolean successful;
private final int playerNumber;
private final String message;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof LogOnResponse))
return false;
final LogOnResponse logOnResponse = (LogOnResponse) o;
if (playerNumber != logOnResponse.playerNumber)
return false;
if (successful != logOnResponse.successful)
return false;
if (message != null ? !message.equals(logOnResponse.message)
: logOnResponse.message != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = (successful ? 1 : 0);
result = 29 * result + playerNumber;
result = 29 * result + (message != null ? message.hashCode() : 0);
return result;
}
private LogOnResponse(boolean success, int i, String s) {
this.successful = success;
this.playerNumber = i;
this.message = s;
}
public static LogOnResponse accepted(int playerNumber) {
return new LogOnResponse(true, playerNumber, null);
}
public static LogOnResponse rejected(String reason) {
return new LogOnResponse(false, -1, reason);
}
public int getPlayerID() {
return playerNumber;
}
public String getMessage() {
return message;
}
public boolean isSuccessful() {
return successful;
}
}

ServerGameModel

Full name: jfreerails.network.specifics.ServerGameModel

Documentation

/**
* Defines methods on a GameModel that let the server load and initiate, and
* save it.
*
* @author Luke
*
*/

Source Code

/**
* Defines methods on a GameModel that let the server load and initiate, and
* save it.
*
* @author Luke
*
*/
public interface ServerGameModel extends GameModel, Serializable {
void setWorld(World w, String[] passwords);
World getWorld();
String[] getPasswords();
void init(MoveReceiver moveExecutor);
void write(ObjectOutputStream objectOut) throws IOException;
}

MovePrecommitter

Full name: jfreerails.network.specifics.MovePrecommitter

Documentation

/**
* The class pre-commits moves we intend to send to the server and either fully
* commits or undoes them depending on the server's response. Note, this class
* does not actually send or receive moves, instead you should call
* <code>toServer(.)</code> when a move has been sent to the server and
* <code>fromServer(.)</code> when a Move or MoveStatus has been received from
* the server.
*
* @author Luke
*
*/

Source Code

/**
* The class pre-commits moves we intend to send to the server and either fully
* commits or undoes them depending on the server's response. Note, this class
* does not actually send or receive moves, instead you should call
* <code>toServer(.)</code> when a move has been sent to the server and
* <code>fromServer(.)</code> when a Move or MoveStatus has been received from
* the server.
*
* @author Luke
*
*/
public class MovePrecommitter {
private static class PreMoveAndMove implements FreerailsSerializable {
private static final long serialVersionUID = 3256443607635342897L;
final Move m;
final PreMove pm;
PreMoveAndMove(PreMove preMove, Move move) {
m = move;
pm = preMove;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof PreMoveAndMove))
return false;
final PreMoveAndMove preMoveAndMove = (PreMoveAndMove) o;
if (m != null ? !m.equals(preMoveAndMove.m)
: preMoveAndMove.m != null)
return false;
if (pm != null ? !pm.equals(preMoveAndMove.pm)
: preMoveAndMove.pm != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = (m != null ? m.hashCode() : 0);
result = 29 * result + (pm != null ? pm.hashCode() : 0);
return result;
}
}
private static final Logger logger = Logger
.getLogger(MovePrecommitter.class.getName());
/**
* Whether the first move on the uncommitted list failed to go through on
* the last try.
*/
boolean blocked = false;
/**
* List of moves and premoves that have been sent to the server and executed
* on the local world object.
*/
final LinkedList<FreerailsSerializable> precomitted = new LinkedList<FreerailsSerializable>();
/**
* List of moves and premoves that have been sent to the server but not
* executed on the local world object.
*/
final LinkedList<FreerailsSerializable> uncomitted = new LinkedList<FreerailsSerializable>();
private final World w;
MovePrecommitter(World w) {
this.w = w;
}
void fromServer(Move m) {
logger.finest("Move from server: " + m.toString());
rollBackPrecommittedMoves();
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
}
/** Indicates that the server has processed a move we sent. */
void fromServer(MoveStatus ms) {
precommitMoves();
if (precomitted.size() > 0) {
Move m = (Move) precomitted.removeFirst();
if (!ms.ok) {
logger.info("Move rejected by server: " + ms.message);
MoveStatus undoStatus = m.undoMove(w, Player.AUTHORITATIVE);
if (!undoStatus.ok) {
throw new IllegalStateException();
}
} else {
logger.finest("Move accepted by server: " + m.toString());
}
} else {
if (!ms.ok) {
logger.fine("Clear the blockage " + ms.message);
uncomitted.removeFirst();
precommitMoves();
} else {
throw new IllegalStateException();
}
}
}
Move fromServer(PreMove pm) {
Move generatedMove = pm.generateMove(w);
fromServer(generatedMove);
return generatedMove;
}
void fromServer(PreMoveStatus pms) {
rollBackPrecommittedMoves();
PreMove pm = (PreMove) uncomitted.removeFirst();
if (pms.ms.ok) {
logger.finest("PreMove accepted by server: " + pms.toString());
Move m = pm.generateMove(w);
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
if (!ms.ok) {
throw new IllegalStateException();
}
} else {
logger.info("PreMove rejected by server: " + pms.ms.message);
}
precommitMoves();
}
void precommitMoves() {
blocked = false;
while (uncomitted.size() > 0 && !blocked) {
Object first = uncomitted.getFirst();
if (first instanceof Move) {
Move m = (Move) first;
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
if (ms.ok) {
uncomitted.removeFirst();
precomitted.addLast(m);
} else {
blocked = true;
}
} else if (first instanceof PreMove) {
PreMove pm = (PreMove) first;
Move m = pm.generateMove(w);
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
if (ms.ok) {
uncomitted.removeFirst();
PreMoveAndMove pmam = new PreMoveAndMove(pm, m);
precomitted.addLast(pmam);
} else {
blocked = true;
}
}
}
}
/**
* Undoes each of the precommitted moves and puts them back on the
* uncommitted list.
*/
private void rollBackPrecommittedMoves() {
while (precomitted.size() > 0) {
Object last = precomitted.removeLast();
Move move2undo;
FreerailsSerializable obj2add2uncomitted;
if (last instanceof Move) {
move2undo = (Move) last;
obj2add2uncomitted = move2undo;
} else if (last instanceof PreMoveAndMove) {
PreMoveAndMove pmam = (PreMoveAndMove) last;
move2undo = pmam.m;
obj2add2uncomitted = pmam.pm;
} else {
throw new IllegalStateException();
}
MoveStatus ms = move2undo.undoMove(w, Player.AUTHORITATIVE);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
uncomitted.addFirst(obj2add2uncomitted);
}
}
void toServer(Move m) {
uncomitted.addLast(m);
precommitMoves();
}
Move toServer(PreMove pm) {
uncomitted.addLast(pm);
precommitMoves();
if (blocked) {
return pm.generateMove(w);
}
PreMoveAndMove pmam = (PreMoveAndMove) precomitted.getLast();
return pmam.m;
}
}

SetPropertyMessage2Client

Full name: jfreerails.network.specifics.SetPropertyMessage2Client

Documentation

/**
* A Message2Client that lets the server set a property (for example, the list
* of saved games available) on a client.
*
* @author Luke
*
*/

Source Code

/**
* A Message2Client that lets the server set a property (for example, the list
* of saved games available) on a client.
*
* @author Luke
*
*/
public class SetPropertyMessage2Client implements Message2Client {
private static final long serialVersionUID = 3544392521746034740L;
private final int id;
private final ClientProperty key;
private final FreerailsSerializable value;
public SetPropertyMessage2Client(int id, ClientProperty key,
FreerailsSerializable value) {
if (null == key || null == value)
throw new NullPointerException();
this.id = id;
this.key = key;
this.value = value;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof SetPropertyMessage2Client))
return false;
final SetPropertyMessage2Client setPropertyMessage2Client = (SetPropertyMessage2Client) o;
if (id != setPropertyMessage2Client.id)
return false;
if (!key.equals(setPropertyMessage2Client.key))
return false;
if (!value.equals(setPropertyMessage2Client.value))
return false;
return true;
}
public MessageStatus execute(ClientControlInterface client) {
client.setProperty(key, value);
return new MessageStatus(id, true);
}
public int getID() {
return id;
}
@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + key.hashCode();
result = 29 * result + value.hashCode();
return result;
}
}

SavedGamesManager

Full name: jfreerails.network.specifics.SavedGamesManager

Documentation

/**
* Defines methods that let the server load and save game states, and get blank
* maps for new games.
*
* @author Luke
*
*/

Source Code

/**
* Defines methods that let the server load and save game states, and get blank
* maps for new games.
*
* @author Luke
*
*/
public interface SavedGamesManager {
String[] getSaveGameNames();
String[] getNewMapNames();
void saveGame(Serializable w, String s) throws IOException;
Serializable loadGame(String name) throws IOException;
Serializable newMap(String name) throws IOException;
}

SaveGameMessage2Server

Full name: jfreerails.network.specifics.SaveGameMessage2Server

Documentation

/**
* A request to save the game.
*
* @author Luke
*
*/

Source Code

/**
* A request to save the game.
*
* @author Luke
*
*/
public class SaveGameMessage2Server implements Message2Server {
private static final long serialVersionUID = 3257281452725777209L;
private final int id;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof SaveGameMessage2Server))
return false;
final SaveGameMessage2Server saveGameMessage2Server = (SaveGameMessage2Server) o;
if (id != saveGameMessage2Server.id)
return false;
if (!filename.equals(saveGameMessage2Server.filename))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + filename.hashCode();
return result;
}
private final String filename;
public SaveGameMessage2Server(int id, String s) {
this.id = id;
this.filename = s;
}
public int getID() {
return id;
}
public MessageStatus execute(ServerControlInterface server) {
try {
server.savegame(filename);
return new MessageStatus(id, true);
} catch (Exception e) {
return new MessageStatus(id, false, e.getMessage());
}
}
}

UntriedMoveReceiver

Full name: jfreerails.network.specifics.UntriedMoveReceiver

Documentation

/**
* Lets the caller test moves.
*
* @author rob
*
*/

Source Code

/**
* Lets the caller test moves.
*
* @author rob
*
*/
public interface UntriedMoveReceiver extends MoveReceiver {
MoveStatus tryDoMove(Move move);
void processPreMove(PreMove pm);
}

SetWorldMessage2Client

Full name: jfreerails.network.specifics.SetWorldMessage2Client

Documentation

/**
* Sent from the server to the client when (i) a new game is started, (ii) a
* game is loaded, or (iii) the client connects to a game in progress.
*
* @author Luke
*
*/

Source Code

/**
* Sent from the server to the client when (i) a new game is started, (ii) a
* game is loaded, or (iii) the client connects to a game in progress.
*
* @author Luke
*
*/
@Immutable
public class SetWorldMessage2Client implements Message2Client {
private static final long serialVersionUID = 3257570619972269362L;
private final int id;
private final World world;
/**
* Note, makes a defensive copy of the world object passed to it.
*/
public SetWorldMessage2Client(int id, World world) {
this.id = id;
this.world = world.defensiveCopy();
}
public MessageStatus execute(ClientControlInterface client) {
client.setGameModel(world.defensiveCopy());
return new MessageStatus(id, true);
}
public int getID() {
return id;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof SetWorldMessage2Client))
return false;
final SetWorldMessage2Client setWorldMessage2Client = (SetWorldMessage2Client) o;
if (id != setWorldMessage2Client.id)
return false;
if (!world.equals(setWorldMessage2Client.world))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + world.hashCode();
return result;
}
}

RefreshListOfGamesMessage2Server

Full name: jfreerails.network.specifics.RefreshListOfGamesMessage2Server

Documentation

/** Tells the server to check the filesystem for changes to the available new maps and saved games.
* @author Luke
* */

Source Code

/** Tells the server to check the filesystem for changes to the available new maps and saved games.
* @author Luke
* */
public class RefreshListOfGamesMessage2Server implements Message2Server {
private static final long serialVersionUID = -8745171955732354168L;
private final int id;
public MessageStatus execute(ServerControlInterface server) {
server.refreshSavedGames();
return new MessageStatus(id, true);
}
public int getID() {
return id;
}
public RefreshListOfGamesMessage2Server(final int id) {
super();
this.id = id;
}
@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final RefreshListOfGamesMessage2Server other = (RefreshListOfGamesMessage2Server) obj;
if (id != other.id)
return false;
return true;
}
}

FreerailsGameServer

Full name: jfreerails.network.specifics.FreerailsGameServer

Documentation

/**
* When executed by a thread, this class does the following: reads and executes
* moves and commands received from connected clients; sends moves and commands
* to connected clients.
*
* @see InetConnectionAccepter
* @see Connection2Client
*
* @author Luke
*
*/

Source Code

/**
* When executed by a thread, this class does the following: reads and executes
* moves and commands received from connected clients; sends moves and commands
* to connected clients.
*
* @see InetConnectionAccepter
* @see Connection2Client
*
* @author Luke
*
*/
public class FreerailsGameServer implements ServerControlInterface, GameServer,
Runnable {
/** Used as a property name for property change events. */
public static final String CONNECTED_PLAYERS = "CONNECTED_PLAYERS";
private static final Logger logger = Logger
.getLogger(FreerailsGameServer.class.getName());
public static FreerailsGameServer startServer(SavedGamesManager gamesManager) {
FreerailsGameServer server = new FreerailsGameServer(gamesManager);
Thread t = new Thread(server);
t.start();
try {
/* Wait for the server to start before returning. */
synchronized (server.status) {
server.status.wait();
}
return server;
} catch (InterruptedException e) {
e.printStackTrace();
throw new IllegalStateException();
}
}
private final HashMap<NameAndPassword, Connection2Client> acceptedConnections = new HashMap<NameAndPassword, Connection2Client>();
private int commandID = 0;
/**
* ID of the last SetWorldMessage2Client sent out. Used to keep track of
* which clients have updated their world object to the current version.
*/
private int confirmationID = Integer.MIN_VALUE; /*
* Don't default 0 to avoid
* mistaken confirmations.
*/
/**
* The players who have confirmed that they have received the last copy of
* the world object sent.
*/
private HashSet<NameAndPassword> confirmedPlayers = new HashSet<NameAndPassword>();
/* Contains the user names of the players who are currently logged on. */
private HashSet<NameAndPassword> currentlyLoggedOn = new HashSet<NameAndPassword>();
private boolean newPlayersAllowed = true;
private ArrayList<NameAndPassword> players = new ArrayList<NameAndPassword>();
private final PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(
this);
private final SavedGamesManager savedGamesManager;
private ServerGameModel serverGameModel = new SimpleServerGameModel();
private final SynchronizedFlag status = new SynchronizedFlag(false);
public FreerailsGameServer(SavedGamesManager gamesManager) {
this.savedGamesManager = gamesManager;
}
public synchronized void addConnection(Connection2Client connection) {
String[] before = getPlayerNames();
logger.fine("Adding connection..");
logger.fine("Waiting for login details..");
try {
LogOnRequest request = (LogOnRequest) connection
.waitForObjectFromClient();
logger.fine("Trying to login player: " + request.getUsername());
LogOnResponse response = this.logon(request);
connection.writeToClient(response);
connection.flush();
NameAndPassword p = new NameAndPassword(request.getUsername(),
request.getPassword());
if (response.isSuccessful()) {
logger.fine("Login successful");
synchronized (acceptedConnections) {
acceptedConnections.put(p, connection);
}
/* Just send to the new client. */
Message2Client setMaps = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.MAPS_AVAILABLE,
new ImStringList(savedGamesManager.getNewMapNames()));
ImStringList savedGameNames = new ImStringList(
savedGamesManager.getSaveGameNames());
Message2Client setSaveGames = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.SAVED_GAMES, savedGameNames);
connection.writeToClient(setMaps);
connection.writeToClient(setSaveGames);
// no need to flush since it is done in
// sendListOfConnectedPlayers2Clients()
/*
* If there is a game in progress, we need to send the client a
* copy of the world object.
*/
if (null != serverGameModel && null != getWorld()) {
SetWorldMessage2Client command = new SetWorldMessage2Client(
confirmationID, getWorld());
connection.writeToClient(command);
}
/* Send to all clients. */
sendListOfConnectedPlayers2Clients();
String[] after = getPlayerNames();
propertyChangeSupport.firePropertyChange("CONNECTED_PLAYERS",
before, after);
} else {
connection.disconnect();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}
public synchronized int countOpenConnections() {
Iterator<NameAndPassword> it = acceptedConnections.keySet().iterator();
int numConnections = 0;
while (it.hasNext()) {
Connection2Client connection = acceptedConnections.get(it.next());
if (connection.isOpen()) {
numConnections++;
}
}
return numConnections;
}
World getCopyOfWorld() {
return this.getWorld().defensiveCopy();
}
private int getNextClientCommandId() {
return commandID++;
}
public String[] getPlayerNames() {
String[] playerNames = new String[players.size()];
for (int i = 0; i < players.size(); i++) {
playerNames[i] = players.get(i).username;
}
return playerNames;
}
private World getWorld() {
return serverGameModel.getWorld();
}
boolean isConfirmed(int player) {
logger.fine("confirmedPlayers.size()=" + confirmedPlayers.size());
boolean isConfirmed = confirmedPlayers.contains(players.get(player));
return isConfirmed;
}
public boolean isNewPlayersAllowed() {
return newPlayersAllowed;
}
private boolean isPlayer(String username) {
for (NameAndPassword p : players) {
if (p.username.equals(username))
return true;
}
return false;
}
public void loadgame(String saveGameName) throws IOException {
logger.info("load game " + saveGameName);
newPlayersAllowed = false;
confirmedPlayers.clear();
ServerGameModel loadedGame;
loadedGame = (ServerGameModel) savedGamesManager.loadGame(saveGameName);
String[] passwords = loadedGame.getPasswords();
World w = loadedGame.getWorld();
assert passwords.length == w.getNumberOfPlayers();
ArrayList<NameAndPassword> newPlayers = new ArrayList<NameAndPassword>();
for (int i = 0; i < passwords.length; i++) {
Player player = w.getPlayer(i);
NameAndPassword nap = new NameAndPassword(player.getName(),
passwords[i]);
newPlayers.add(nap);
}
/*
* Remove any currently logged on players who are not participants in
* the game we are loading.
*/
for (NameAndPassword nap : players) {
if (!newPlayers.contains(nap) && currentlyLoggedOn.contains(nap)) {
removeConnection(nap);
}
}
players = newPlayers;
setServerGameModel(loadedGame);
sendWorldUpdatedCommand();
}
public void logoff(int player) {
NameAndPassword np = players.get(player);
currentlyLoggedOn.remove(np);
}
public LogOnResponse logon(LogOnRequest lor) {
NameAndPassword p = new NameAndPassword(lor.getUsername(), lor
.getPassword());
boolean isReturningPlayer = isPlayer(lor.getUsername());
if (!this.newPlayersAllowed && !isReturningPlayer) {
return LogOnResponse.rejected("New logins not allowed.");
}
if (currentlyLoggedOn.contains(p)) {
return LogOnResponse.rejected("Already logged on.");
}
if (isReturningPlayer) {
if (!players.contains(p)) {
return LogOnResponse.rejected("Incorrect password.");
}
} else {
players.add(p);
}
currentlyLoggedOn.add(p);
return LogOnResponse.accepted(players.indexOf(p));
}
public void newGame(String mapName, int numAI) {
for (int i = 0; i < numAI; ++i) {
NameAndPassword aiPlayer = new NameAndPassword("AI" + i, null);
players.add(aiPlayer);
}
this.newGame(mapName);
}
public void newGame(String mapName) {
newPlayersAllowed = false;
confirmedPlayers.clear();
try {
World world = (World) savedGamesManager.newMap(mapName);
String[] passwords = new String[players.size()];
/* Add players to world. */
for (int i = 0; i < players.size(); i++) {
String name = players.get(i).username;
Player p = new Player(name, i);
Move addPlayerMove = AddPlayerMove.generateMove(world, p);
MoveStatus ms = addPlayerMove.doMove(world, Player.AUTHORITATIVE);
if(!ms.ok) throw new IllegalStateException();
passwords[i] = players.get(i).password;
}
serverGameModel.setWorld(world, passwords);
setServerGameModel(serverGameModel);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendWorldUpdatedCommand();
logger.fine("newGame");
}
private void removeConnection(NameAndPassword p) throws IOException {
String[] before = getPlayerNames();
Connection2Client connection = acceptedConnections.get(p);
/*
* Fix for bug 1047439 Shutting down remote client crashes server We get
* an IllegalStateException if we try to disconnect a connection that is
* not open.
*/
if (connection.isOpen()) {
connection.disconnect();
}
this.currentlyLoggedOn.remove(p);
String[] after = getPlayerNames();
propertyChangeSupport.firePropertyChange("CONNECTED_PLAYERS", before,
after);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}
public void run() {
status.open();
status.close();
}
public void savegame(String saveGameName) {
logger.info("save game as " + saveGameName);
try {
savedGamesManager.saveGame(serverGameModel, saveGameName);
String[] saves = savedGamesManager.getSaveGameNames();
Message2Client request = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.SAVED_GAMES, new ImStringList(
saves));
send2All(request);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void send2All(FreerailsSerializable message) {
send2AllExcept(null, message);
}
/** Sends the specified message to all connections except the specified one. */
private void send2AllExcept(Connection2Client dontSend2,
FreerailsSerializable message) {
Iterator<NameAndPassword> it = acceptedConnections.keySet().iterator();
while (it.hasNext()) {
NameAndPassword p = it.next();
Connection2Client connection = acceptedConnections.get(p);
if (dontSend2 != connection) {
try {
connection.writeToClient(message);
connection.flush();
} catch (Exception e) {
if (connection.isOpen()) {
e.printStackTrace();
try {
removeConnection(p);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
}
private void sendListOfConnectedPlayers2Clients() throws IOException {
/* Send the client the list of players. */
String[] playerNames = getPlayerNames();
Message2Client request = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.CONNECTED_CLIENTS, new ImStringList(
playerNames));
send2All(request);
}
private void sendWorldUpdatedCommand() {
/* Send the world to the clients. */
confirmationID = getNextClientCommandId();
SetWorldMessage2Client command = new SetWorldMessage2Client(
confirmationID, getWorld());
send2All(command);
}
public void setNewPlayersAllowed(boolean newPlayersAllowed) {
this.newPlayersAllowed = newPlayersAllowed;
}
public void setServerGameModel(ServerGameModel serverGameModel) {
this.serverGameModel = serverGameModel;
MoveReceiver moveExecutor = new MoveReceiver() {
public void processMove(Move move) {
MoveStatus ms = move.doMove(getWorld(), Player.AUTHORITATIVE);
if (ms.ok) {
send2All(move);
} else {
logger.warning(ms.message);
}
}
};
serverGameModel.init(moveExecutor);
}
public void stop() {
// TODO Auto-generated method stub
}
public void stopGame() {
logger.info("Stop game.");
}
/**
* Updates the game model, then reads and deals with the outstanding
* messages from each of the connected clients. This method is synchronized
* to prevent moves being sent out while addConnection(.) is executing.
*/
public synchronized void update() {
if (null != serverGameModel) {
serverGameModel.update();
}
try {
Iterator<NameAndPassword> it = acceptedConnections.keySet()
.iterator();
while (it.hasNext()) {
NameAndPassword player = it.next();
Connection2Client connection = acceptedConnections.get(player);
if (connection.isOpen()) {
FreerailsSerializable[] messages = connection
.readFromClient();
for (int i = 0; i < messages.length; i++) {
if (messages[i] instanceof Message2Server) {
Message2Server message2 = (Message2Server) messages[i];
MessageStatus cStatus = message2.execute(this);
logger.fine(message2.toString());
connection.writeToClient(cStatus);
} else if (messages[i] instanceof MessageStatus) {
MessageStatus messageStatus = (MessageStatus) messages[i];
if (messageStatus.getId() == this.confirmationID) {
/*
* The client is confirming that they have
* updated their world object to the current
* version.
*/
this.confirmedPlayers.add(player);
logger.fine("Confirmed player " + player);
}
logger.fine(messages[i].toString());
} else if (messages[i] instanceof Move
|| messages[i] instanceof PreMove) {
Player player2 = getWorld().getPlayer(
players.indexOf(player));
FreerailsPrincipal principal = player2
.getPrincipal();
Move move;
boolean isMove = messages[i] instanceof Move;
if (isMove) {
move = (Move) messages[i];
} else {
PreMove pm = (PreMove) messages[i];
move = pm.generateMove(getWorld());
}
MoveStatus mStatus = move.tryDoMove(
this.getWorld(), principal);
if (mStatus.isOk()) {
move.doMove(getWorld(), principal);
/*
* We don't send the move to the client that
* submitted it.
*/
send2AllExcept(connection, move);
}
if (isMove) {
connection.writeToClient(mStatus);
} else {
connection.writeToClient(PreMoveStatus
.fromMoveStatus(mStatus));
}
} else {
logger.fine(messages[i].toString());
}
}
connection.flush();
} else {
/* Remove connection. */
this.removeConnection(player);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void refreshSavedGames() {
Message2Client setMaps = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.MAPS_AVAILABLE,
new ImStringList(savedGamesManager.getNewMapNames()));
ImStringList savedGameNames = new ImStringList(
savedGamesManager.getSaveGameNames());
Message2Client setSaveGames = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.SAVED_GAMES, savedGameNames);
send2All(setMaps);
send2All(setSaveGames);
}
}

SimpleServerGameModel

Full name: jfreerails.network.specifics.SimpleServerGameModel

Documentation

/**
* A ServerGameModel that has a world object but no automation.
*
* @author Luke
*
*/

Source Code

/**
* A ServerGameModel that has a world object but no automation.
*
* @author Luke
*
*/
public class SimpleServerGameModel implements ServerGameModel {
private static final long serialVersionUID = 3546074757457131826L;
private World w;
private String[] passwords;
public void setWorld(World w, String[] passwords) {
this.w = w;
this.passwords = passwords.clone();
}
public World getWorld() {
return w;
}
public void init(MoveReceiver moveExecuter) {
}
public void write(ObjectOutputStream objectOut) throws IOException {
}
public void update() {
}
public void listUpdated(KEY key, int index, FreerailsPrincipal principal) {
}
public void itemAdded(KEY key, int index, FreerailsPrincipal principal) {
}
public void itemRemoved(KEY key, int index, FreerailsPrincipal principal) {
}
public String[] getPasswords() {
return passwords.clone();
}
}

LogOnRequest

Full name: jfreerails.network.specifics.LogOnRequest

Documentation

/**
* A client sends an instance of this class to the server when it wishes to log
* on.
*
* @author Luke
*
*/

Source Code

/**
* A client sends an instance of this class to the server when it wishes to log
* on.
*
* @author Luke
*
*/
public class LogOnRequest implements FreerailsSerializable {
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof LogOnRequest))
return false;
final LogOnRequest logOnRequest = (LogOnRequest) o;
if (password != null ? !password.equals(logOnRequest.password)
: logOnRequest.password != null)
return false;
if (username != null ? !username.equals(logOnRequest.username)
: logOnRequest.username != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = (username != null ? username.hashCode() : 0);
result = 29 * result + (password != null ? password.hashCode() : 0);
return result;
}
private static final long serialVersionUID = 3257854263924240949L;
private final String username;
private final String password;
public LogOnRequest(String username, String password) {
this.username = username;
this.password = password;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
}

FreerailsClient

Full name: jfreerails.network.specifics.FreerailsClient

Documentation

/**
* A client for FreerailsGameServer.
*
* @author Luke
*
*/

Source Code

/**
* A client for FreerailsGameServer.
*
* @author Luke
*
*/
public class FreerailsClient implements ClientControlInterface, GameModel,
UntriedMoveReceiver, ServerCommandReceiver {
private static final Logger logger = Logger.getLogger(FreerailsClient.class
.getName());
protected Connection2Server connection2Server;
private final HashMap<String, Serializable> properties = new HashMap<String, Serializable>();
private final MoveChainFork moveFork;
private World world;
private MovePrecommitter committer;
public FreerailsClient() {
moveFork = new MoveChainFork();
}
public final MoveChainFork getMoveFork() {
return moveFork;
}
/**
* Connects this client to a remote server.
*/
public final LogOnResponse connect(String address, int port,
String username, String password) {
logger.fine("Connect to remote server. " + address + ":" + port);
try {
connection2Server = new InetConnection2Server(address, port);
} catch (IOException e) {
return LogOnResponse.rejected(e.getMessage());
}
try {
LogOnRequest request = new LogOnRequest(username, password);
connection2Server.writeToServer(request);
connection2Server.flush();
LogOnResponse response = (LogOnResponse) connection2Server
.waitForObjectFromServer();
return response;
} catch (Exception e) {
try {
connection2Server.disconnect();
} catch (IOException e1) {
e1.printStackTrace();
}
return LogOnResponse.rejected(e.getMessage());
}
}
/**
* Connects this client to a local server.
*/
public final LogOnResponse connect(GameServer server, String username,
String password) {
try {
LogOnRequest request = new LogOnRequest(username, password);
connection2Server = new LocalConnection();
connection2Server.writeToServer(request);
server.addConnection((LocalConnection) connection2Server);
LogOnResponse response = (LogOnResponse) connection2Server
.waitForObjectFromServer();
return response;
} catch (Exception e) {
try {
connection2Server.disconnect();
} catch (IOException e1) {
e1.printStackTrace();
}
return LogOnResponse.rejected(e.getMessage());
}
}
/**
* Disconnect the client from the server.
*/
public final void disconnect() {
try {
connection2Server.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
public final void setGameModel(FreerailsMutableSerializable o) {
world = (World) o;
committer = new MovePrecommitter(world);
newWorld(world);
}
/**
* Subclasses should override this method if they need to respond the the
* world being changed.
*/
protected void newWorld(World w) {
}
public void setProperty(ClientProperty propertyName, Serializable value) {
properties.put(propertyName.name(), value);
}
public final Serializable getProperty(ClientProperty propertyName) {
return properties.get(propertyName.name());
}
public final void resetProperties(HashMap newProperties) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}
final FreerailsSerializable read() {
try {
return this.connection2Server.waitForObjectFromServer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
throw new IllegalStateException();
}
final void write(FreerailsSerializable fs) {
try {
connection2Server.writeToServer(fs);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException();
}
}
/** Reads and deals with all outstanding messages from the server. */
final public void update() {
try {
FreerailsSerializable[] messages = connection2Server
.readFromServer();
for (int i = 0; i < messages.length; i++) {
FreerailsSerializable message = messages[i];
processMessage(message);
}
connection2Server.flush();
clientUpdates();
} catch (IOException e) {
ReportBugTextGenerator.unexpectedException(e);
}
}
/**
* Empty method called by update(), subclasses should override this method
* instead of overriding update().
*
*/
protected void clientUpdates() {
}
/** Processes a message received from the server. */
final void processMessage(FreerailsSerializable message) throws IOException {
if (message instanceof Message2Client) {
Message2Client request = (Message2Client) message;
MessageStatus status = request.execute(this);
logger.fine(request.toString());
connection2Server.writeToServer(status);
} else if (message instanceof Move) {
Move m = (Move) message;
committer.fromServer(m);
moveFork.processMove(m);
} else if (message instanceof MoveStatus) {
MoveStatus ms = (MoveStatus) message;
committer.fromServer(ms);
} else if (message instanceof PreMove) {
PreMove pm = (PreMove) message;
Move m = committer.fromServer(pm);
moveFork.processMove(m);
} else if (message instanceof PreMoveStatus) {
PreMoveStatus pms = (PreMoveStatus) message;
committer.fromServer(pms);
} else {
logger.fine(message.toString());
}
}
final public World getWorld() {
return world;
}
/** Sends move to the server. */
final public void processMove(Move move) {
committer.toServer(move);
moveFork.processMove(move);
write(move);
}
/** Tests a move before sending it to the server. */
final public MoveStatus tryDoMove(Move move) {
return move.tryDoMove(world, Player.AUTHORITATIVE);
}
public void sendCommand(Message2Server c) {
write(c);
}
public void processPreMove(PreMove pm) {
Move m = committer.toServer(pm);
moveFork.processMove(m);
write(pm);
}
protected long getLastTickTime(){
return moveFork.getLastTickTime();
}
}

SavedGamesManager4UnitTests

Full name: jfreerails.network.specifics.SavedGamesManager4UnitTests

Documentation

/**
* Stores saved games in memory rather than on disk.
*
* @author Luke
*
*/

Source Code

/**
* Stores saved games in memory rather than on disk.
*
* @author Luke
*
*/
public class SavedGamesManager4UnitTests implements SavedGamesManager {
private String[] mapsAvailable = { "map1", "map2" };
private final HashMap<String, Serializable> savedGames = new HashMap<String, Serializable>();
public String[] getSaveGameNames() {
Object[] keys = savedGames.keySet().toArray();
String[] names = new String[keys.length];
for (int i = 0; i < names.length; i++) {
names[i] = (String) keys[i];
}
return names;
}
public String[] getNewMapNames() {
return mapsAvailable.clone();
}
public void saveGame(Serializable w, String name) throws IOException {
// Make a copy so that the saved version's state cannot be changed.
Serializable copy = Utils.cloneBySerialisation(w);
this.savedGames.put(name, copy);
}
public Serializable loadGame(String name) throws IOException {
Serializable o = savedGames.get(name);
return Utils.cloneBySerialisation(o);
}
public Serializable newMap(String name) throws IOException {
return new WorldImpl(10, 10);
}
}

ServerCommandReceiver

Full name: jfreerails.network.specifics.ServerCommandReceiver

Documentation

/**
* Defines a method that accepts a command to be sent to the server.
*
* @author Luke
*
*/

Source Code

/**
* Defines a method that accepts a command to be sent to the server.
*
* @author Luke
*
*/
public interface ServerCommandReceiver {
void sendCommand(Message2Server c);
}

Methods

NameAndPassword

Full name: jfreerails.network.specifics.NameAndPassword

Documentation

/**
* Used by the server to store a player's username and password.
*
* @author Luke
*
*/

Source Code

/**
* Used by the server to store a player's username and password.
*
* @author Luke
*
*/
public class NameAndPassword implements Serializable {
private static final long serialVersionUID = 3258409551740155956L;
public final String password;
public final String username;
public NameAndPassword(String u, String p) {
username = u;
password = p;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof NameAndPassword))
return false;
NameAndPassword test = (NameAndPassword) obj;
return test.password.equals(password) && test.username.equals(username);
}
@Override
public int hashCode() {
int result = 17;
result = result * 37 + password.hashCode();
result = result * 37 + username.hashCode();
return result;
}
@Override
public String toString() {
return username;
}
}

LoadGameMessage2Server

Full name: jfreerails.network.specifics.LoadGameMessage2Server

Documentation

/**
* Request to load a game.
*
* @author Luke
*
*/

Source Code

/**
* Request to load a game.
*
* @author Luke
*
*/
public class LoadGameMessage2Server implements Message2Server {
private static final long serialVersionUID = 3256726186552930869L;
private final int id;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof LoadGameMessage2Server))
return false;
final LoadGameMessage2Server loadGameMessage2Server = (LoadGameMessage2Server) o;
if (id != loadGameMessage2Server.id)
return false;
if (!filename.equals(loadGameMessage2Server.filename))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + filename.hashCode();
return result;
}
private final String filename;
public LoadGameMessage2Server(int id, String s) {
this.id = id;
this.filename = s;
}
public int getID() {
return id;
}
public MessageStatus execute(ServerControlInterface server) {
try {
server.loadgame(filename);
return new MessageStatus(id, true);
} catch (Exception e) {
e.printStackTrace();
return new MessageStatus(id, false, e.getMessage());
}
}
}

LauncherInterface

Full name: jfreerails.launcher.LauncherInterface

Documentation

/**
* Exposes the methods on the Launcher that the launcher panels may call.
*
* @author Luke
*
*/

Source Code

/**
* Exposes the methods on the Launcher that the launcher panels may call.
*
* @author Luke
*
*/
public interface LauncherInterface {
public static final int INFO = 0;
public static final int WARNING = 1;
public static final int ERROR = 2;
void setInfoText(String text, int status);
void setNextEnabled(boolean enabled);
void hideErrorMessages();
void hideAllMessages();
void setProperty(String key, String value);
String getProperty(String key);
void saveProps();
}

Launcher

Full name: jfreerails.launcher.Launcher

Documentation

/**
* Launcher GUI for both the server and/or client.
*
* TODO The code in the switch statements needs reviewing.
*
* @author rtuck99@users.sourceforge.net
* @author Luke
*/

Source Code

/**
* Launcher GUI for both the server and/or client.
*
* TODO The code in the switch statements needs reviewing.
*
* @author rtuck99@users.sourceforge.net
* @author Luke
*/
public class Launcher extends javax.swing.JFrame implements LauncherInterface {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(Launcher.class
.getName());
private static String QUICKSTART = "-quickstart";
private final Component[] wizardPages = new Component[4];
private int currentPage = 0;
private FreerailsGameServer server;
private GUIClient client;
private Properties props;
private final ImageIcon errorIcon = new javax.swing.ImageIcon(getClass()
.getResource("/jfreerails/client/graphics/icons/error.gif"));
private final ImageIcon warningIcon = new javax.swing.ImageIcon(getClass()
.getResource("/jfreerails/client/graphics/icons/warning.gif"));
private final ImageIcon infoIcon = new javax.swing.ImageIcon(getClass()
.getResource("/jfreerails/client/graphics/icons/info.gif"));
private final ProgressJPanel progressPanel = new ProgressJPanel(this);
public void setNextEnabled(boolean enabled) {
nextButton.setEnabled(enabled);
if (nextIsStart) {
nextButton.setText("Start");
} else {
nextButton.setText("Next...");
}
}
private boolean nextIsStart = false;
private void startGame() {
CardLayout cl = (CardLayout) jPanel1.getLayout();
cl.show(jPanel1, "4");
setButtonsVisible(false);
LauncherPanel1 lp = (LauncherPanel1) wizardPages[0];
SelectMapJPanel msp = (SelectMapJPanel) wizardPages[1];
ClientOptionsJPanel cop = (ClientOptionsJPanel) wizardPages[2];
ConnectedPlayersJPanel cp = (ConnectedPlayersJPanel) wizardPages[3];
boolean recover = false;
int mode;
switch (lp.getMode()) {
case LauncherPanel1.MODE_SINGLE_PLAYER:
try {
mode = cop.getScreenMode();
client = new GUIClient(cop.getPlayerName(), progressPanel,
mode, cop.getDisplayMode());
if (isNewGame()) {
initServer();
}
client.connect(server, cop.getPlayerName(), "password");
setServerGameModel();
} catch (IOException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} finally {
if (recover) {
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setButtonsVisible(true);
currentPage = 1;
cl.show(jPanel1, "1");
return;
}
}
startThread(server, client);
break;
case LauncherPanel1.MODE_START_NETWORK_GAME:
// LL: I don't think this code ever executes now that there is a
// connected players screen.
try {
setServerGameModel();
currentPage = 3;
String[] playerNames = server.getPlayerNames();
playerNames = playerNames.length == 0 ? new String[] { "No players are connected." }
: playerNames;
cp.setListOfPlayers(playerNames);
cl.show(jPanel1, "3");
setNextEnabled(false);
} catch (IOException e) {
// We end up here if an Exception was thrown when loading a
// saved game.
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} finally {
if (recover) {
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setNextEnabled(true);
currentPage = 1;
setButtonsVisible(true);
cl.show(jPanel1, "1");
return;
}
}
break;
case LauncherPanel1.MODE_JOIN_NETWORK_GAME:
mode = cop.getScreenMode();
try {
InetSocketAddress serverInetAddress = cop
.getRemoteServerAddress();
if (null == serverInetAddress) {
throw new NullPointerException("Couldn't resolve hostname.");
}
String playerName = cop.getPlayerName();
client = new GUIClient(playerName, progressPanel, mode, cop
.getDisplayMode());
String hostname = serverInetAddress.getHostName();
int port = serverInetAddress.getPort();
setInfoText("Connecting to server...", LauncherInterface.INFO);
LogOnResponse logOnResponse = client.connect(hostname, port,
playerName, "password");
if (logOnResponse.isSuccessful()) {
setInfoText("Logged on and waiting for game to start.", LauncherInterface.INFO);
startThread(client);
} else {
recover = true;
setInfoText(logOnResponse.getMessage(),
LauncherInterface.WARNING);
}
} catch (IOException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} catch (NullPointerException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} finally {
if (recover) {
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setButtonsVisible(true);
cl.show(jPanel1, "2");
return;
}
}
break;
case LauncherPanel1.MODE_SERVER_ONLY:
if (msp.validateInput()) {
initServer();
try {
setServerGameModel();
prepare2HostNetworkGame(msp.getServerPort());
setNextEnabled(true);
} catch (NullPointerException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} catch (IOException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} finally {
if (recover) {
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setButtonsVisible(true);
return;
}
}
}
}// End of switch statement
}
private void setServerGameModel() throws IOException {
ClientOptionsJPanel cop = (ClientOptionsJPanel) wizardPages[2];
if (isNewGame()) {
SelectMapJPanel msp2 = (SelectMapJPanel) wizardPages[1];
server.newGame(msp2.getNewMapName());
cop.limitPlayerNames(null);
} else {
// Do nothing since the server is already set up.
}
}
private boolean isNewGame() {
SelectMapJPanel msp2 = (SelectMapJPanel) wizardPages[1];
return msp2.getSelection().equals(SelectMapJPanel.Selection.NEW_GAME);
}
/** Starts the client and server in the same thread. */
private static void startThread(final FreerailsGameServer server,
final GUIClient client) {
try {
Runnable run = new Runnable() {
public void run() {
while (null == client.getWorld()) {
client.update();
server.update();
}
GameModel[] models = new GameModel[] { client, server };
ScreenHandler screenHandler = client.getScreenHandler();
GameLoop gameLoop = new GameLoop(screenHandler, models);
//screenHandler.apply();
gameLoop.run();
}
};
Thread t = new Thread(run, "Client + server main loop");
t.start();
} catch (Exception e) {
exit(e);
}
}
/** Starts the client in a new thread. */
private void startThread(final GUIClient guiClient) {
try {
Runnable run = new Runnable() {
public void run() {
while (null == guiClient.getWorld()) {
guiClient.update();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// do nothing
}
}
GameModel[] models = new GameModel[] { guiClient };
ScreenHandler screenHandler = guiClient.getScreenHandler();
GameLoop gameLoop = new GameLoop(screenHandler, models);
gameLoop.run();
}
};
Thread t = new Thread(run, "Client main loop");
t.start();
} catch (Exception e) {
exit(e);
}
}
/** Starts the server in a new thread. */
private static void startThread(final FreerailsGameServer server) {
try {
Runnable r = new Runnable() {
public void run() {
while (true) {
long startTime = System.currentTimeMillis();
server.update();
long deltatime = System.currentTimeMillis() - startTime;
if (deltatime < 20) {
try {
Thread.sleep(20 - deltatime);
} catch (InterruptedException e) {
// do nothing.
}
}
}
}
};
Thread t = new Thread(r, "FreerailsGameServer");
t.start();
} catch (Exception e) {
exit(e);
}
}
private void initServer() {
SavedGamesManager gamesManager = new SavedGamesManagerImpl();
server = new FreerailsGameServer(gamesManager);
ServerGameModelImpl serverGameModel = new ServerGameModelImpl();
server.setServerGameModel(serverGameModel);
/*
* Set the server field on the connected players panel so that it can
* keep track of who is connected.
*/
ConnectedPlayersJPanel cp = (ConnectedPlayersJPanel) wizardPages[3];
cp.server = server;
server.addPropertyChangeListener(cp);
cp.updateListOfPlayers();
}
/**
* Runs the game.
*/
public static void main(String args[]) {
//SynchronizedEventQueue.use();
// Let the user know if we are using a custom logging config.
String loggingProperties = System
.getProperty("java.util.logging.config.file");
if (null != loggingProperties) {
logger.info("Logging properties file: " + loggingProperties);
}
logger.fine("Started launcher.");
boolean quickstart = false;
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (QUICKSTART.equals(args[i]))
quickstart = true;
}
}
Launcher launcher = new Launcher(quickstart);
launcher.start(quickstart);
}
/**
* Shows GUI. If <code>quickstart</code> is <code>true</code> runs the
* game.
*
* @param quickstart
* boolean
*/
public void start(boolean quickstart) {
setVisible(true);
if (quickstart) {
startGame();
}
}
/** Starts a thread listening for new connections. */
private void prepare2HostNetworkGame(int port) throws IOException {
loadProps();
if (isNewGame()) {
initServer();
}
InetConnectionAccepter accepter = new InetConnectionAccepter(port,
server);
/*
* Note, the thread's name gets set in the run method so there is no
* point setting it here.
*/
Thread t = new Thread(accepter);
t.start();
CardLayout cl = (CardLayout) jPanel1.getLayout();
cl.show(jPanel1, "3");
currentPage = 3;
}
public Launcher(boolean quickstart) {
loadProps();
initComponents();
wizardPages[0] = new LauncherPanel1(this);
wizardPages[1] = new SelectMapJPanel(this);
wizardPages[2] = new ClientOptionsJPanel(this);
wizardPages[3] = new ConnectedPlayersJPanel();
if (!quickstart) {
jPanel1.add(wizardPages[0], "0");
jPanel1.add(wizardPages[1], "1");
jPanel1.add(wizardPages[2], "2");
jPanel1.add(wizardPages[3], "3");
jPanel1.add(progressPanel, "4");
pack();
} else {
prevButton.setVisible(false);
nextButton.setVisible(false);
pack();
}
hideAllMessages();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
nextButton = new javax.swing.JButton();
prevButton = new javax.swing.JButton();
infoLabel = new javax.swing.JLabel();
getContentPane().setLayout(new java.awt.GridBagLayout());
setTitle("Freerails Launcher");
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
jPanel1.setLayout(new java.awt.CardLayout());
jPanel1.setPreferredSize(new java.awt.Dimension(400, 300));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(jPanel1, gridBagConstraints);
nextButton.setText("Next...");
nextButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(nextButton, gridBagConstraints);
prevButton.setText("Back...");
prevButton.setEnabled(false);
prevButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
prevButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(prevButton, gridBagConstraints);
infoLabel.setText("Error messages go here!");
infoLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
infoLabel.setMinimumSize(new java.awt.Dimension(20, 20));
infoLabel.setPreferredSize(new java.awt.Dimension(20, 20));
infoLabel.setVerifyInputWhenFocusTarget(false);
infoLabel.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(infoLabel, gridBagConstraints);
pack();
}// GEN-END:initComponents
private void prevButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_prevButtonActionPerformed
CardLayout cl = (CardLayout) jPanel1.getLayout();
nextIsStart = false;
hideAllMessages();
switch (currentPage) {
case 1:
cl.previous(jPanel1);
currentPage--;
prevButton.setEnabled(false);
break;
case 2:
LauncherPanel1 panel = (LauncherPanel1) wizardPages[0];
if (panel.getMode() == LauncherPanel1.MODE_JOIN_NETWORK_GAME) {
currentPage = 0;
cl.show(jPanel1, "0");
prevButton.setEnabled(false);
} else {
currentPage--;
cl.previous(jPanel1);
}
}
}// GEN-LAST:event_prevButtonActionPerformed
private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_nextButtonActionPerformed
try {
CardLayout cl = (CardLayout) jPanel1.getLayout();
LauncherPanel1 panel = (LauncherPanel1) wizardPages[0];
SelectMapJPanel msp = (SelectMapJPanel) wizardPages[1];
ClientOptionsJPanel cop = (ClientOptionsJPanel) wizardPages[2];
hideAllMessages();
switch (currentPage) {
case 0:
msp.validateInput();
/* Initial game selection page */
switch (panel.getMode()) {
case LauncherPanel1.MODE_SERVER_ONLY:
/* go to map selection screen */
cl.next(jPanel1);
msp.setServerPortPanelVisible(true);
currentPage++;
break;
case LauncherPanel1.MODE_SINGLE_PLAYER:
/* go to map selection screen */
cl.next(jPanel1);
msp.setServerPortPanelVisible(false);
cop.setRemoteServerPanelVisible(false);
currentPage++;
break;
case LauncherPanel1.MODE_START_NETWORK_GAME:
/* go to map selection screen */
msp.setServerPortPanelVisible(true);
cop.setRemoteServerPanelVisible(false);
cl.next(jPanel1);
currentPage++;
break;
case LauncherPanel1.MODE_JOIN_NETWORK_GAME:
/* client display options */
nextIsStart = true;
cl.show(jPanel1, "2");
currentPage = 2;
msp.setServerPortPanelVisible(false);
cop.setRemoteServerPanelVisible(true);
cop.limitPlayerNames(null);
break;
}
prevButton.setEnabled(true);
break;
case 1:
/* map selection page */
if (panel.getMode() == LauncherPanel1.MODE_SERVER_ONLY) {
if (msp.validateInput()) {
prevButton.setEnabled(false);
try {
if (!isNewGame()) {
initServer();
server
.loadgame(ServerControlInterface.FREERAILS_SAV);
}
prepare2HostNetworkGame(msp.getServerPort());
} catch (BindException be) {
// When the port is already in use.
prevButton.setEnabled(true);
setInfoText(be.getMessage(),
LauncherInterface.WARNING);
}
}
} else {
if (isNewGame()) {
cop.limitPlayerNames(null);
} else {
initServer();
server.loadgame(msp.getSaveGameName());
String[] playernames = server.getPlayerNames();
cop.limitPlayerNames(playernames);
}
nextIsStart = true;
prevButton.setEnabled(true);
setNextEnabled(true);
currentPage++;
cl.next(jPanel1);
}
break;
case 2:
/* display mode selection */
if (panel.getMode() == LauncherPanel1.MODE_START_NETWORK_GAME) {
if (msp.validateInput()) {
prevButton.setEnabled(false);
int mode = cop.getScreenMode();
prepare2HostNetworkGame(msp.getServerPort());
client = new GUIClient(cop.getPlayerName(),
progressPanel, mode, cop.getDisplayMode());
client.connect(server, cop.getPlayerName(), "password");
}
} else {
prevButton.setEnabled(false);
cop.setControlsEnabled(false);
startGame();
}
break;
case 3:
try {
/* Connection status screen */
prevButton.setEnabled(false);
setServerGameModel();// TODO catch exception
if (panel.getMode() == LauncherPanel1.MODE_START_NETWORK_GAME) {
startThread(server, client);
cl.show(jPanel1, "4");
} else {
/* Start a stand alone server. */
startThread(server);
setVisible(false);
}
setButtonsVisible(false);
setNextEnabled(false);
} catch (IOException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setNextEnabled(true);
currentPage = 1;
cl.show(jPanel1, "1");
return;
}
break;
default:
throw new IllegalArgumentException(String.valueOf(currentPage));
}
} catch (Exception e) {
exit(e);
}
}// GEN-LAST:event_nextButtonActionPerformed
private static void exit(Exception e) {
ReportBugTextGenerator.unexpectedException(e);
}
/** Exit the Application. */
private void exitForm(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_exitForm
System.exit(0);
}// GEN-LAST:event_exitForm
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JLabel infoLabel;
javax.swing.JPanel jPanel1;
javax.swing.JButton nextButton;
javax.swing.JButton prevButton;
// End of variables declaration//GEN-END:variables
public void setInfoText(String text, int status) {
infoLabel.setText(text);
switch (status) {
case LauncherInterface.ERROR:
infoLabel.setIcon(errorIcon);
nextButton.setEnabled(false);
break;
case LauncherInterface.INFO:
infoLabel.setIcon(infoIcon);
nextButton.setEnabled(true);
break;
case LauncherInterface.WARNING:
infoLabel.setIcon(warningIcon);
nextButton.setEnabled(true);
break;
default:
throw new IllegalArgumentException(String.valueOf(status));
}
}
public void hideAllMessages() {
infoLabel.setText(null);
infoLabel.setIcon(null);
nextButton.setEnabled(true);
}
public void setButtonsVisible(boolean b){
nextButton.setVisible(b);
prevButton.setVisible(b);
}
public void hideErrorMessages() {
if (infoLabel.getIcon() == errorIcon) {
infoLabel.setText(null);
infoLabel.setIcon(null);
nextButton.setEnabled(true);
}
}
private void loadProps(){
try{
props = new Properties();
FileInputStream in = new FileInputStream("freerails.properties");
props.load(in);
in.close();
if(!props.containsKey("freerails.server.port") ||
!props.containsKey("freerails.server.port") ||
!props.containsKey("freerails.server.port")){
throw new Exception();
}
}catch (Exception e){
props = new Properties();
props.setProperty("freerails.server.port", "55000");
props.setProperty("freerails.player.name", System.getProperty("user.name"));
props.setProperty("freerails.server.ip.address", "127.0.0.1");
}
}
public void saveProps(){
try{
FileOutputStream out = new FileOutputStream("freerails.properties");
props.store(out, "---No Comment---");
out.close();
//Copy key-value pairs to System.Properties so
//that they are visible in the game via the
//show java properties menu item.
System.getProperties().putAll(props);
}catch (Exception e){
logger.warning(e.getMessage());
}
}
public void setProperty(String key, String value){
props.setProperty(key, value);
}
public String getProperty(String key){
return props.getProperty(key);
}
}

LauncherPanel1

Full name: jfreerails.launcher.LauncherPanel1

Documentation

/**
* The first launcher panel, lets you choose 'single player', 'start network
* game' etc.
*
* @author rtuck99@users.sourceforge.net
*/

Source Code

/**
* The first launcher panel, lets you choose 'single player', 'start network
* game' etc.
*
* @author rtuck99@users.sourceforge.net
*/
final class LauncherPanel1 extends javax.swing.JPanel {
private static final long serialVersionUID = 3257850965422913590L;
static final int MODE_SINGLE_PLAYER = 0;
static final int MODE_START_NETWORK_GAME = 1;
static final int MODE_JOIN_NETWORK_GAME = 2;
static final int MODE_SERVER_ONLY = 3;
private final ButtonModel[] buttonModels = new ButtonModel[4];
int getMode() {
for (int i = 0; i < buttonModels.length; i++) {
if (buttonGroup1.getSelection() == buttonModels[i]) {
return i;
}
}
assert false;
return 0;
}
/*
* private void validateSettings() { boolean isValid = false; String
* infoText = null;
*
* switch (getMode()) {
*
* case MODE_SINGLE_PLAYER: isValid = true; break; case
* MODE_START_NETWORK_GAME: case MODE_SERVER_ONLY: isValid = true; break;
* case MODE_JOIN_NETWORK_GAME: isValid = true; break; }
* owner.setInfoText(infoText, LauncherInterface.WARNING);
* owner.setNextEnabled(isValid); }
*/
public LauncherPanel1(LauncherInterface owner) {
initComponents();
buttonModels[MODE_SINGLE_PLAYER] = singlePlayerButton.getModel();
buttonModels[MODE_START_NETWORK_GAME] = startNetworkButton.getModel();
buttonModels[MODE_JOIN_NETWORK_GAME] = joinNetworkButton.getModel();
buttonModels[MODE_SERVER_ONLY] = serverOnlyButton.getModel();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
buttonGroup1 = new javax.swing.ButtonGroup();
singlePlayerButton = new javax.swing.JRadioButton();
startNetworkButton = new javax.swing.JRadioButton();
joinNetworkButton = new javax.swing.JRadioButton();
serverOnlyButton = new javax.swing.JRadioButton();
paddingJPanel = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
setBorder(new javax.swing.border.TitledBorder(
new javax.swing.border.EtchedBorder(), "Select Game Type"));
buttonGroup1.add(singlePlayerButton);
singlePlayerButton.setSelected(true);
singlePlayerButton.setText("Single-Player");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(singlePlayerButton, gridBagConstraints);
buttonGroup1.add(startNetworkButton);
startNetworkButton.setText("Start a network game");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(startNetworkButton, gridBagConstraints);
buttonGroup1.add(joinNetworkButton);
joinNetworkButton.setText("Join a network game");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(joinNetworkButton, gridBagConstraints);
buttonGroup1.add(serverOnlyButton);
serverOnlyButton.setText("Server only");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(serverOnlyButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(paddingJPanel, gridBagConstraints);
}// GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.ButtonGroup buttonGroup1;
javax.swing.JRadioButton joinNetworkButton;
javax.swing.JPanel paddingJPanel;
javax.swing.JRadioButton serverOnlyButton;
javax.swing.JRadioButton singlePlayerButton;
javax.swing.JRadioButton startNetworkButton;
// End of variables declaration//GEN-END:variables
}

ClientOptionsJPanel

Full name: jfreerails.launcher.ClientOptionsJPanel

Documentation

/**
* The Launcher panel that lets you choose fullscreen or windowed mode and the
* screen resolution etc.
*
* @author rtuck99@users.sourceforge.net
* @author Luke Lindsay
*/

Source Code

/**
* The Launcher panel that lets you choose fullscreen or windowed mode and the
* screen resolution etc.
*
* @author rtuck99@users.sourceforge.net
* @author Luke Lindsay
*/
class ClientOptionsJPanel extends javax.swing.JPanel implements LauncherPanel {
private static final long serialVersionUID = 3256721779883325748L;
private static final Logger logger = Logger
.getLogger(ClientOptionsJPanel.class.getName());
private final LauncherInterface owner;
private String[] names;
private static final String INVALID_PORT = "A valid port value is between between 0 and 65535.";
private final DocumentListener documentListener = new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
validateInput();
}
public void removeUpdate(DocumentEvent e) {
validateInput();
}
public void changedUpdate(DocumentEvent e) {
validateInput();
}
};
/**
* If the user has opted to load a game, we need to limit the list of
* players to participants in the game we are loading. Otherwise, any player
* name is OK. Either, pass in a array of names or null if any name is OK.
*/
void limitPlayerNames(String[] n) {
this.names = n;
if (names == null) {
playerName.setVisible(true);
playerNames.setVisible(false);
playerName.setEditable(true);
} else {
if (names.length == 1) {
playerName.setVisible(true);
playerNames.setVisible(false);
playerName.setText(n[0]);
playerName.setEditable(false);
} else {
playerName.setVisible(false);
playerNames.setVisible(true);
ComboBoxModel model = new DefaultComboBoxModel(names);
playerNames.setModel(model);
}
}
this.revalidate();
}
String getPlayerName() {
if (playerName.isVisible()) {
return playerName.getText();
}
int index = playerNames.getSelectedIndex();
if (index < 0)
return null; // no selection.
return names[index];
}
DisplayMode getDisplayMode() {
if (this.fullScreenButton.isSelected()) {
MyDisplayMode displayMode = ((MyDisplayMode) jList1
.getSelectedValue());
logger.fine("The selected display mode is "
+ displayMode.toString());
return displayMode.displayMode;
}
return null;
}
InetSocketAddress getRemoteServerAddress() {
String portStr = remotePort.getText();
if (portStr == null) {
return null;
}
int port;
try {
port = Integer.parseInt(portStr);
} catch (NumberFormatException e) {
return null;
}
InetSocketAddress address;
try {
address = new InetSocketAddress(remoteIP.getText(), port);
} catch (IllegalArgumentException e) {
return null;
}
/*
* cut and pasted InetSocketAddress isa = getRemoteServerAddress(); if
* (isa == null) { infoText = "Please enter a valid remote server
* address"; } else if (isa.isUnresolved()) { infoText = "Couldn't
* resolve remote server address"; } else { isValid = true; }
*/
return address;
}
public boolean validateInput() {
/* Validate player name. */
if (playerName.getText() == null || playerName.getText().equals("")) {
owner.setInfoText("Please set a name for your player",
LauncherInterface.ERROR);
return false;
}
/* Validate host name. */
if (remoteIP.getText() == null || remoteIP.getText().equals("")) {
owner.setInfoText("Please enter a host name",
LauncherInterface.ERROR);
return false;
}
/* Validate port. */
try {
int port = Integer.parseInt(remotePort.getText());
if (port < 0 || port > 65535) {
owner.setInfoText(INVALID_PORT, LauncherInterface.ERROR);
return false;
}
} catch (Exception e) {
owner.setInfoText(INVALID_PORT, LauncherInterface.ERROR);
return false;
}
/*
* Validate display-mode selection. Note, on some systems the display
* mode can't be changed, in which case the list of selectable display
* modes will have length 0.
*/
if (fullScreenButton.isSelected() && jList1.getModel().getSize() > 0
&& jList1.getSelectedIndex() == -1) {
owner
.setInfoText("Select a display-mode.",
LauncherInterface.ERROR);
return false;
}
/* Everything is ok. */
owner.hideErrorMessages();
owner.setProperty("freerails.server.port", this.remotePort.getText());
owner.setProperty("freerails.player.name", this.playerName.getText());
owner.setProperty("freerails.server.ip.address", this.remoteIP.getText());
owner.saveProps();
return true;
}
int getScreenMode() {
if (this.fullScreenButton.isSelected()) {
return ScreenHandler.FULL_SCREEN;
} else if (this.windowedButton.isSelected()) {
return ScreenHandler.WINDOWED_MODE;
} else if (this.fixedSizeButton.isSelected()) {
return ScreenHandler.FIXED_SIZE_WINDOWED_MODE;
} else {
throw new IllegalStateException();
}
}
public void setControlsEnabled(boolean enabled) {
windowedButton.setEnabled(enabled);
fullScreenButton.setEnabled(enabled);
fixedSizeButton.setEnabled(enabled);
if (fullScreenButton.isSelected()) {
jList1.setEnabled(enabled);
}
}
private final DisplayModesComboBoxModels listModel;
void setRemoteServerPanelVisible(boolean b) {
this.jPanel4.setVisible(b);
}
public ClientOptionsJPanel(LauncherInterface owner) {
this.owner = owner;
initComponents();
listModel = new DisplayModesComboBoxModels();
listModel.removeDisplayModesBelow(640, 480, 16);
jList1.setModel(listModel);
jList1.setSelectedIndex(0);
validateInput();
// Listen for changes in the server port text box.
remotePort.getDocument().addDocumentListener(documentListener);
remoteIP.getDocument().addDocumentListener(documentListener);
playerName.getDocument().addDocumentListener(documentListener);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel3 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
playerName = new javax.swing.JTextField();
playerNames = new javax.swing.JComboBox();
jPanel4 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
remoteIP = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
remotePort = new javax.swing.JTextField();
spacer = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jPanel2 = new javax.swing.JPanel();
windowedButton = new javax.swing.JRadioButton();
fixedSizeButton = new javax.swing.JRadioButton();
fullScreenButton = new javax.swing.JRadioButton();
setLayout(new java.awt.GridBagLayout());
addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
jPanel3.setBorder(new javax.swing.border.TitledBorder(
new javax.swing.border.EtchedBorder(), "Player Details"));
jLabel1.setText("Player name:");
jPanel3.add(jLabel1);
playerName.setColumns(12);
playerName.setText(owner.getProperty("freerails.player.name"));
jPanel3.add(playerName);
playerNames.setToolTipText("Select a player from the saved game.");
jPanel3.add(playerNames);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
add(jPanel3, gridBagConstraints);
jPanel4.setLayout(new java.awt.GridBagLayout());
jPanel4
.setBorder(new javax.swing.border.TitledBorder(
new javax.swing.border.EtchedBorder(),
"Remote server address"));
jPanel4.setEnabled(false);
jLabel2.setText("IP Address:");
jPanel4.add(jLabel2, new java.awt.GridBagConstraints());
remoteIP.setColumns(15);
remoteIP.setText(owner.getProperty("freerails.server.ip.address"));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel4.add(remoteIP, gridBagConstraints);
jLabel3.setText("port");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel4.add(jLabel3, gridBagConstraints);
remotePort.setColumns(5);
remotePort.setText(owner.getProperty("freerails.server.port"));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel4.add(remotePort, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
jPanel4.add(spacer, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
add(jPanel4, gridBagConstraints);
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel1.setBorder(new javax.swing.border.TitledBorder(
new javax.swing.border.EtchedBorder(), "Select Display Mode"));
jScrollPane1.setBorder(new javax.swing.border.BevelBorder(
javax.swing.border.BevelBorder.LOWERED));
jList1
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.setEnabled(false);
jList1
.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(
javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jScrollPane1.setViewportView(jList1);
jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);
jPanel2.setLayout(new javax.swing.BoxLayout(jPanel2,
javax.swing.BoxLayout.Y_AXIS));
buttonGroup1.add(windowedButton);
windowedButton.setSelected(true);
windowedButton.setText("Windowed");
jPanel2.add(windowedButton);
buttonGroup1.add(fixedSizeButton);
fixedSizeButton.setText("Windowed (fixed size 640*480)");
jPanel2.add(fixedSizeButton);
buttonGroup1.add(fullScreenButton);
fullScreenButton.setText("Full screen");
fullScreenButton
.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
fullScreenButtonStateChanged(evt);
}
});
jPanel2.add(fullScreenButton);
jPanel1.add(jPanel2, java.awt.BorderLayout.NORTH);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jPanel1, gridBagConstraints);
}// GEN-END:initComponents
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {// GEN-FIRST:event_jList1ValueChanged
validateInput();
}// GEN-LAST:event_jList1ValueChanged
private void formComponentShown(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_formComponentShown
validateInput();
}// GEN-LAST:event_formComponentShown
private void fullScreenButtonStateChanged(javax.swing.event.ChangeEvent evt) {// GEN-FIRST:event_fullScreenButtonStateChanged
jList1.setEnabled(fullScreenButton.isSelected());
validateInput();
}// GEN-LAST:event_fullScreenButtonStateChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.ButtonGroup buttonGroup1;
javax.swing.JRadioButton fixedSizeButton;
javax.swing.JRadioButton fullScreenButton;
javax.swing.JLabel jLabel1;
javax.swing.JLabel jLabel2;
javax.swing.JLabel jLabel3;
javax.swing.JList jList1;
javax.swing.JPanel jPanel1;
javax.swing.JPanel jPanel2;
javax.swing.JPanel jPanel3;
javax.swing.JPanel jPanel4;
javax.swing.JScrollPane jScrollPane1;
javax.swing.JTextField playerName;
javax.swing.JComboBox playerNames;
javax.swing.JTextField remoteIP;
javax.swing.JTextField remotePort;
javax.swing.JPanel spacer;
javax.swing.JRadioButton windowedButton;
// End of variables declaration//GEN-END:variables
}

ProgressJPanel

Full name: jfreerails.launcher.ProgressJPanel

Documentation

/**
* A JPanel that displays a splash screen and a progress bar.
*
* @author Luke
*/

Source Code

/**
* A JPanel that displays a splash screen and a progress bar.
*
* @author Luke
*/
public class ProgressJPanel extends javax.swing.JPanel implements
FreerailsProgressMonitor{
private static final long serialVersionUID = 3256445798203273776L;
int step, stepSize;
final int numSteps = 5;
LauncherInterface owner;
public void setValue(int i) {
int value = i * 100 / stepSize;
value += 100 * step;
progressBar.setValue(value);
}
public void nextStep(int max) {
//So that the waiting for game to start message
//goes away.
owner.hideAllMessages();
step++;
stepSize = max;
if(numSteps < step)
throw new IllegalStateException();
}
public void finished() {
if(numSteps-1 != step)
throw new IllegalStateException(numSteps +"!="+ step);
getTopLevelAncestor().setVisible(false);
}
/** Creates new form ProgressJPanel */
public ProgressJPanel(LauncherInterface owner) {
this.owner = owner;
initComponents();
progressBar.setMaximum(numSteps * 100);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
progressBar = new javax.swing.JProgressBar();
splashImage = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(3, 7, 3, 7);
add(progressBar, gridBagConstraints);
splashImage.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
splashImage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jfreerails/client/graphics/splash_screen.jpg")));
add(splashImage, new java.awt.GridBagConstraints());
}
// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JProgressBar progressBar;
javax.swing.JLabel splashImage;
// End of variables declaration//GEN-END:variables
}

ConnectedPlayersJPanel

Full name: jfreerails.launcher.ConnectedPlayersJPanel

Documentation

/**
* A JPanel that shows the players currently logged in to the server.
*
* @author Luke
*/

Source Code

/**
* A JPanel that shows the players currently logged in to the server.
*
* @author Luke
*/
public class ConnectedPlayersJPanel extends javax.swing.JPanel implements
PropertyChangeListener {
private static final long serialVersionUID = 4049080453489111344L;
FreerailsGameServer server = null;
/** Creates new form ConnectedPlayersJPanel */
public ConnectedPlayersJPanel() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
title = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
setLayout(new java.awt.GridBagLayout());
title.setText("Connected Players");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(title, gridBagConstraints);
jList1.setModel(new javax.swing.AbstractListModel() {
private static final long serialVersionUID = 1L;
String[] strings = { "No players are logged on!" };
public int getSize() {
return strings.length;
}
public Object getElementAt(int i) {
return strings[i];
}
});
jScrollPane1.setViewportView(jList1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}// GEN-END:initComponents
void updateListOfPlayers() {
if (null != server) {
String[] playerNames = server.getPlayerNames();
playerNames = playerNames.length == 0 ? new String[] { "No players are logged on!" }
: playerNames;
setListOfPlayers(playerNames);
}
}
void setListOfPlayers(String[] players) {
jList1.setListData(players);
}
/** Called by the server when a player is added or removed. */
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(FreerailsGameServer.CONNECTED_PLAYERS)) {
if (EventQueue.isDispatchThread()) {
updateListOfPlayers();
} else {
EventQueue.invokeLater(new Runnable() {
public void run() {
updateListOfPlayers();
}
});
}
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JList jList1;
javax.swing.JScrollPane jScrollPane1;
javax.swing.JLabel title;
// End of variables declaration//GEN-END:variables
}

SelectMapJPanel

Full name: jfreerails.launcher.SelectMapJPanel

Documentation

/**
* The Launcher panel that lets you load a game or start a new game with a
* choice of maps.
* @author Luke
*/

Source Code

/**
* The Launcher panel that lets you load a game or start a new game with a
* choice of maps.
* @author Luke
*/
public class SelectMapJPanel extends javax.swing.JPanel implements LauncherPanel {
private static final long serialVersionUID = 3763096353857024568L;
private static final String SELECT_A_MAP = "Select a map.";
private static final String INVALID_PORT = "A valid port value is between between 0 and 65535.";
private final LauncherInterface owner;
public enum Selection {NONE, NEW_GAME, LOAD_GAME};
Selection getSelection() {
if( newmapsJList.getSelectedIndex() != -1 ){
savedmapsJList.setSelectedIndex(-1);
return Selection.NEW_GAME;
}
if(savedmapsJList.getSelectedIndex() != -1){
return Selection.LOAD_GAME;
}
return Selection.NONE;
}
void setServerPortPanelVisible(boolean b) {
this.jPanel3.setVisible(b);
}
public String getNewMapName() {
return (String) newmapsJList.getSelectedValue();
}
public String getSaveGameName() {
return (String) savedmapsJList.getSelectedValue();
}
SelectMapJPanel(LauncherInterface owner) {
this.owner = owner;
initComponents();
/* initialise the map list */
SavedGamesManagerImpl sgm = new SavedGamesManagerImpl();
newmapsJList.setListData(sgm.getNewMapNames());
newmapsJList.setSelectedIndex(0);
savedmapsJList.setListData(sgm.getSaveGameNames());
owner.setNextEnabled(true);
// Listen for changes in the server port text box.
serverPort.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
validateInput();
}
public void removeUpdate(DocumentEvent e) {
validateInput();
}
public void changedUpdate(DocumentEvent e) {
validateInput();
}
});
}
int getServerPort() {
String s = serverPort.getText();
return Integer.parseInt(s);
}
public boolean validateInput() {
/* Validate map selection. */
if (this.getSelection().equals(Selection.NONE)) {
owner.setInfoText(SELECT_A_MAP, LauncherInterface.ERROR);
return false;
}
/* Validate port. */
try {
int port = getServerPort();
if (port < 0 || port > 65535) {
owner.setInfoText(INVALID_PORT, LauncherInterface.ERROR);
return false;
}
} catch (Exception e) {
owner.setInfoText(INVALID_PORT, LauncherInterface.ERROR);
return false;
}
/* Everything is ok. */
owner.hideErrorMessages();
owner.setProperty("freerails.server.port", this.serverPort.getText());
owner.saveProps();
return true;
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
newmapsJList = new javax.swing.JList();
jPanel4 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
savedmapsJList = new javax.swing.JList();
jPanel3 = new javax.swing.JPanel();
portLabel = new javax.swing.JLabel();
serverPort = new javax.swing.JTextField();
jPanel2 = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel1.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), "New Game"));
jPanel1.setPreferredSize(null);
jScrollPane1.setViewportBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
newmapsJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
newmapsJList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
newmapsJListValueChanged(evt);
}
});
jScrollPane1.setViewportView(newmapsJList);
jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jPanel1, gridBagConstraints);
jPanel4.setLayout(new java.awt.BorderLayout());
jPanel4.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), "Load game"));
jPanel4.setPreferredSize(null);
jPanel4.setRequestFocusEnabled(false);
jScrollPane2.setViewportBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
savedmapsJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
savedmapsJList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
savedmapsJListValueChanged(evt);
}
});
jScrollPane2.setViewportView(savedmapsJList);
jPanel4.add(jScrollPane2, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jPanel4, gridBagConstraints);
jPanel3.setLayout(new java.awt.GridBagLayout());
jPanel3.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), "Server port"));
portLabel.setText("Port:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel3.add(portLabel, gridBagConstraints);
serverPort.setColumns(6);
serverPort.setText( owner.getProperty("freerails.server.port"));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel3.add(serverPort, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
jPanel3.add(jPanel2, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
add(jPanel3, gridBagConstraints);
}
// </editor-fold>//GEN-END:initComponents
private void savedmapsJListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_savedmapsJListValueChanged
if(savedmapsJList.getSelectedIndex() != -1)
newmapsJList.clearSelection();
validateInput();
}//GEN-LAST:event_savedmapsJListValueChanged
private void newmapsJListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_newmapsJListValueChanged
if(newmapsJList.getSelectedIndex() != -1)
savedmapsJList.clearSelection();
validateInput();
}//GEN-LAST:event_newmapsJListValueChanged
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JPanel jPanel1;
javax.swing.JPanel jPanel2;
javax.swing.JPanel jPanel3;
javax.swing.JPanel jPanel4;
javax.swing.JScrollPane jScrollPane1;
javax.swing.JScrollPane jScrollPane2;
javax.swing.JList newmapsJList;
javax.swing.JLabel portLabel;
javax.swing.JList savedmapsJList;
javax.swing.JTextField serverPort;
// End of variables declaration//GEN-END:variables
}

LauncherPanel

Full name: jfreerails.launcher.LauncherPanel

Documentation

/**
* @author Luke
*
*/

Source Code

/**
* @author Luke
*
*/
public interface LauncherPanel {
boolean validateInput();
}

Methods

GUIClient

Full name: jfreerails.launcher.GUIClient

Documentation

/**
* A swing freerails client.
*
* @author Luke
*
*/

Source Code

/**
* A swing freerails client.
*
* @author Luke
*
*/
public class GUIClient extends FreerailsClient implements
FreerailsProgressMonitor {
public static void main(String[] args) {
try {
GUIClient client = new GUIClient("Test", null,
ScreenHandler.WINDOWED_MODE, null);
client.start();
} catch (IOException e) {
e.printStackTrace();
}
}
private final ActionRoot actionRoot;
private final GUIComponentFactoryImpl factory;
private final ModelRootImpl modelRoot;
private final FreerailsProgressMonitor monitor;
private final String name;
private final ScreenHandler screenHandler;
private RenderersRoot vl;
public GUIClient(String name, FreerailsProgressMonitor fm, int screenMode,
DisplayMode dm) throws IOException {
this.name = name;
this.monitor = null == fm ? this : fm;
// Set up model root and action root.
modelRoot = new ModelRootImpl();
modelRoot.setMoveFork(this.getMoveFork());
modelRoot.setMoveReceiver(this);
modelRoot.setServerCommandReceiver(this);
actionRoot = new ActionRoot(modelRoot);
// Create GUI components
factory = new GUIComponentFactoryImpl(modelRoot, actionRoot);
JFrame createClientJFrame = factory.createClientJFrame(name);
screenHandler = new ScreenHandler(createClientJFrame, screenMode, dm);
}
@Override
protected void clientUpdates() {
if (factory.isSetup()) {
factory.getBuildTrackController().update();
// Update sub tick time.
long currentTime = System.currentTimeMillis();
long lastTick = getLastTickTime();
double dt = currentTime - lastTick;
ReadOnlyWorld world2 = modelRoot.getWorld();
GameSpeed gameSpeed = (GameSpeed) world2.get(ITEM.GAME_SPEED);
GameTime currentGameTime = world2.currentTime();
double ticks = currentGameTime.getTicks();
if(!gameSpeed.isPaused()){
double milliSecondsPerTick = 1000/ gameSpeed.getSpeed();
double subTicks = dt / milliSecondsPerTick;
subTicks = Math.min(dt, 1d);
ticks += subTicks;
}
modelRoot.setProperty(Property.TIME, new Double(ticks));
}
}
public void finished() {
// TODO Auto-generated method stub
}
public ScreenHandler getScreenHandler() {
return screenHandler;
}
@Override
protected void newWorld(World w) {
try {
if (null == vl || !vl.validate(w)) {
try {
vl = new RenderersRootImpl(w, monitor);
monitor.finished();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Should be a smarter way of doing this..
for (int player = 0; player < w.getNumberOfPlayers(); player++) {
Player p = w.getPlayer(player);
if (p.getName().equals(this.name)) {
modelRoot.setup(w, p.getPrincipal());
}
}
modelRoot.setProperty(ModelRoot.Property.SERVER, connection2Server
.getServerDetails());
actionRoot.setup(modelRoot, vl);
factory.setup(vl, w);
} catch (Exception e) {
ReportBugTextGenerator.unexpectedException(e);
}
}
public void nextStep(int max) {
// TODO Auto-generated method stub
}
public void setMessage(String s) {
System.out.println(s);
}
public void setValue(int i) {
// TODO Auto-generated method stub
}
@Override
public void setProperty(ClientProperty propertyName, Serializable value) {
super.setProperty(propertyName, value);
switch (propertyName) {
case SAVED_GAMES:
modelRoot.setProperty(Property.SAVED_GAMES_LIST, value);
break;
default:
break;
}
}
void start() {
// Set up world.
SavedGamesManager gamesManager = new SavedGamesManagerImpl();
FreerailsGameServer server = new FreerailsGameServer(gamesManager);
String mapName = gamesManager.getNewMapNames()[0];
ServerGameModelImpl serverGameModel = new ServerGameModelImpl();
server.setServerGameModel(serverGameModel);
this.connect(server, name, "password");
server.newGame(mapName);
while (null == this.getWorld()) {
this.update();
server.update();
}
GameModel[] models = new GameModel[] { this, server };
// Start the game loop
GameLoop gameLoop = new GameLoop(screenHandler, models);
Thread t = new Thread(gameLoop);
t.start();
}
}

JFrameMinimumSizeEnforcer

Full name: jfreerails.controller.JFrameMinimumSizeEnforcer

Documentation

/**
* Since there is no setMinimum size method on JFrame, we use an instance of
* this class to do the job.
*
* @author Luke
*
*/

Source Code

/**
* Since there is no setMinimum size method on JFrame, we use an instance of
* this class to do the job.
*
* @author Luke
*
*/
public class JFrameMinimumSizeEnforcer implements ComponentListener {
private final int minWidth;
private final int minHeight;
public JFrameMinimumSizeEnforcer(int w, int h) {
this.minHeight = h;
this.minWidth = w;
}
public void componentResized(ComponentEvent arg0) {
Component c = arg0.getComponent();
int width = c.getWidth();
int height = c.getHeight();
// we check if either the width
// or the height are below minimum
boolean resize = false;
if (width < minWidth) {
resize = true;
width = minWidth;
}
if (height < minHeight) {
resize = true;
height = minHeight;
}
if (resize) {
c.setSize(width, height);
}
}
public void componentMoved(ComponentEvent arg0) {
}
public void componentShown(ComponentEvent arg0) {
}
public void componentHidden(ComponentEvent arg0) {
}
}

AddTrainPreMove

Full name: jfreerails.controller.AddTrainPreMove

Documentation

/**
* @author Luke
*
*/

Source Code

/**
* @author Luke
*
*/
public class AddTrainPreMove implements PreMove {
private static final long serialVersionUID = 4050201951105069624L;
private final int engineTypeId;
private final ImInts wagons;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof AddTrainPreMove)) {
return false;
}
final AddTrainPreMove addTrainPreMove = (AddTrainPreMove) o;
if (engineTypeId != addTrainPreMove.engineTypeId) {
return false;
}
if (!point.equals(addTrainPreMove.point)) {
return false;
}
if (!principal.equals(addTrainPreMove.principal)) {
return false;
}
if (!schedule.equals(addTrainPreMove.schedule)) {
return false;
}
if (!wagons.equals(addTrainPreMove.wagons)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result;
result = engineTypeId;
result = 29 * result + point.hashCode();
result = 29 * result + principal.hashCode();
result = 29 * result + schedule.hashCode();
return result;
}
private final ImPoint point;
private final FreerailsPrincipal principal;
private final ImmutableSchedule schedule;
public AddTrainPreMove(int e, ImInts wags, ImPoint p,
FreerailsPrincipal fp, ImmutableSchedule s) {
engineTypeId = e;
wagons = wags;
point = p;
principal = fp;
schedule = s;
if (null == wags) {
throw new NullPointerException();
}
if (null == p) {
throw new NullPointerException();
}
if (null == fp) {
throw new NullPointerException();
}
if (null == s) {
throw new NullPointerException();
}
}
PathOnTiles initPositionStep1(ReadOnlyWorld w) {
PositionOnTrack[] pp = FlatTrackExplorer.getPossiblePositions(w, point);
FlatTrackExplorer fte = new FlatTrackExplorer(w, pp[0]);
List<Step> steps = new ArrayList<Step>();
int length = calTrainLength();
int distanceTravelled = 0;
PositionOnTrack p = new PositionOnTrack();
while (distanceTravelled < length) {
fte.nextEdge();
fte.moveForward();
p.setValuesFromInt(fte.getPosition());
Step v = p.cameFrom();
distanceTravelled += v.getLength();
steps.add(v);
}
return new PathOnTiles(point, steps);
}
private int calTrainLength() {
TrainModel train = new TrainModel(engineTypeId, wagons, 0);
int length = train.getLength();
return length;
}
TrainMotion initPositionStep2(PathOnTiles path) {
// TODO fix code.
TrainMotion tm = new TrainMotion(path, path.steps(), calTrainLength(),
ConstAcc.STOPPED);
return tm;
}
/**
* Generates a move that does the following.
* <ol>
* <li>Adds the train</li>
* <li>Adds a cargo bundle to represent the cargo the train is
* carrying</li>
* <li>Adds a schedule for the train</li>
* <li>Adds transaction to pay for the train</li>
* <li>Init. the trains position and motion</li>
* </ol>
*
*
*/
public Move generateMove(ReadOnlyWorld w) {
// Add cargo bundle.
int bundleId = w.size(principal, KEY.CARGO_BUNDLES);
ImmutableCargoBundle cargo = ImmutableCargoBundle.EMPTY_BUNDLE;
AddItemToListMove addCargoBundle = new AddItemToListMove(
KEY.CARGO_BUNDLES, bundleId, cargo, principal);
// Add schedule
for (int i = 0; i < schedule.getNumOrders(); i++) {
TrainOrdersModel order = schedule.getOrder(i);
if (!w.boundsContain(principal, KEY.STATIONS, order.stationId)) {
throw new ArrayIndexOutOfBoundsException(String.format("%d", order.stationId));
}
}
int scheduleId = w.size(principal, KEY.TRAIN_SCHEDULES);
AddItemToListMove addSchedule = new AddItemToListMove(
KEY.TRAIN_SCHEDULES, scheduleId, schedule, principal);
// Add train to train list.
TrainModel train = new TrainModel(engineTypeId, wagons, scheduleId,
bundleId);
int trainId = w.size(principal, KEY.TRAINS);
AddItemToListMove addTrain = new AddItemToListMove(KEY.TRAINS, trainId,
train, principal);
// Pay for train.
int quantity = 1;
/* Determine the price of the train. */
EngineType engineType = (EngineType) w.get(SKEY.ENGINE_TYPES,
engineTypeId);
Money price = engineType.getPrice();
Transaction transaction = new AddItemTransaction(
Transaction.Category.TRAIN, engineTypeId, quantity, new Money(
-price.getAmount()));
AddTransactionMove transactionMove = new AddTransactionMove(principal,
transaction);
// Setup and add train position.
PathOnTiles path = initPositionStep1(w);
TrainMotion motion = initPositionStep2(path);
Move addPosition = new AddActiveEntityMove(motion, trainId,
principal);
return new CompositeMove(addCargoBundle, addSchedule, addTrain,
transactionMove, addPosition);
}
}

OpenList

Full name: jfreerails.controller.OpenList

Documentation

/**
* An OpenList for SimpleAStarPathFinder.
*
* @author Luke
*
*/

Source Code

/**
* An OpenList for SimpleAStarPathFinder.
*
* @author Luke
*
*/
class OpenList implements Serializable {
private static final long serialVersionUID = 3257282539419611442L;
static class OpenListEntry implements Comparable<OpenListEntry>,
Serializable {
private static final long serialVersionUID = -4873508719707382681L;
final int f;
final int node;
OpenListEntry(int _f, int _node) {
this.f = _f;
this.node = _node;
}
public int compareTo(OpenListEntry o) {
// XXX Work around for JDK Bug ID: 6207984
if (f == o.f) {
return node - o.node;
}
return f - o.f;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof OpenListEntry))
return false;
final OpenListEntry openListEntry = (OpenListEntry) o;
if (f != openListEntry.f)
return false;
if (node != openListEntry.node)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = f;
result = 29 * result + node;
return result;
}
@Override
public String toString() {
return "OpenListEntry{node=" + node + ", f=" + f + "}";
}
}
private HashMap<Integer, OpenListEntry> map = new HashMap<Integer, OpenListEntry>();
private PriorityQueue<OpenListEntry> queue = new PriorityQueue<OpenListEntry>();
public OpenList() {
}
void clear() {
queue.clear();
map.clear();
}
int getF(int node) {
int f = map.get(node).f;
return f;
}
void add(int node, int f) {
if (map.containsKey(node)) {
OpenListEntry old = map.get(node);
queue.remove(old);
map.remove(node);
}
OpenList.OpenListEntry entry = new OpenListEntry(f, node);
queue.offer(entry);
map.put(node, entry);
}
boolean contains(int node) {
boolean containsKey = map.containsKey(node);
return containsKey;
}
int smallestF() {
OpenListEntry entry = queue.peek();
return entry.f;
}
int popNodeWithSmallestF() {
OpenListEntry entry = queue.remove();
int node = entry.node;
OpenListEntry removed = map.remove(node);
if (null == removed) {
System.out.println("Shizer, size =" + queue.size());
}
return node;
}
int size() {
return queue.size();
}
}

TrackPathFinder

Full name: jfreerails.controller.TrackPathFinder

Documentation

/**
* Finds the best route to build track between two points.
*
* @author Luke
*
*/

Source Code

/**
* Finds the best route to build track between two points.
*
* @author Luke
*
*/
public class TrackPathFinder implements IncrementalPathFinder {
private static final Logger logger = Logger.getLogger(TrackPathFinder.class
.getName());
private SimpleAStarPathFinder pathFinder = new SimpleAStarPathFinder();
private final ReadOnlyWorld world;
private ImPoint startPoint;
private final FreerailsPrincipal principal;
public TrackPathFinder(ReadOnlyWorld world, FreerailsPrincipal principal) {
this.world = world;
this.principal = principal;
}
public void abandonSearch() {
pathFinder.abandonSearch();
}
private List<ImPoint> convertPath2Points(IntArray path) {
PositionOnTrack progress = new PositionOnTrack();
List<ImPoint> proposedTrack = new ArrayList<ImPoint>();
ImPoint p;
for (int i = 0; i < path.size(); i++) {
progress.setValuesFromInt(path.get(i));
p = new ImPoint(progress.getX(), progress.getY());
proposedTrack.add(p);
logger.fine("Adding point " + p);
}
return proposedTrack;
}
private int[] findTargets(ImPoint targetPoint) {
FreerailsTile tile = (FreerailsTile) world.getTile(targetPoint.x,
targetPoint.y);
TrackPiece trackPiece = tile.getTrackPiece();
int ruleNumber = trackPiece.getTrackTypeID();
int[] targetInts;
if (tile.hasTrack()) {
/*
* If there is already track here, we need to check what directions
* we can build in without creating an illegal track config.
*/
TrackRule trackRule = (TrackRule) world.get(SKEY.TRACK_RULES,
ruleNumber);
/* Count number of possible directions. */
ArrayList<Step> possibleDirections = new ArrayList<Step>();
for (int i = 0; i < 8; i++) {
Step direction = Step.getInstance(i);
TrackConfiguration config = trackPiece.getTrackConfiguration();
TrackConfiguration testConfig = TrackConfiguration.add(config,
direction);
if (trackRule.trackPieceIsLegal(testConfig)) {
possibleDirections.add(direction);
}
}
/* Put them into an array. */
targetInts = new int[possibleDirections.size()];
for (int i = 0; i < targetInts.length; i++) {
Step direction = possibleDirections.get(i);
PositionOnTrack targetPot = PositionOnTrack.createFacing(
targetPoint.x, targetPoint.y, direction);
targetInts[i] = targetPot.toInt();
}
} else {
/* If there is no track here, we can go in any direction. */
targetInts = new int[8];
for (int i = 0; i < 8; i++) {
PositionOnTrack targetPot = PositionOnTrack.createComingFrom(
targetPoint.x, targetPoint.y, Step.getInstance(i));
targetInts[i] = targetPot.toInt();
}
}
return targetInts;
}
public List generatePath(ImPoint start, ImPoint targetPoint,
BuildTrackStrategy bts) throws PathNotFoundException {
setupSearch(start, targetPoint, bts);
pathFinder.search(-1);
IntArray path = pathFinder.retrievePath();
List proposedTrack = convertPath2Points(path);
return proposedTrack;
}
public int getStatus() {
return pathFinder.getStatus();
}
public List<ImPoint> pathAsPoints() {
IntArray path = pathFinder.retrievePath();
return convertPath2Points(path);
}
public Step[] pathAsVectors() {
IntArray path = pathFinder.retrievePath();
int size = path.size();
Step[] vectors = new Step[size];
PositionOnTrack progress = new PositionOnTrack();
int x = startPoint.x;
int y = startPoint.y;
for (int i = 0; i < size; i++) {
progress.setValuesFromInt(path.get(i));
int x2 = progress.getX();
int y2 = progress.getY();
vectors[i] = Step.getInstance(x2 - x, y2 - y);
x = x2;
y = y2;
}
return vectors;
}
public void search(long maxDuration) throws PathNotFoundException {
pathFinder.search(maxDuration);
}
public void setupSearch(ImPoint startPoint, ImPoint targetPoint,
BuildTrackStrategy bts) throws PathNotFoundException {
logger
.fine("Find track path from " + startPoint + " to "
+ targetPoint);
this.startPoint = startPoint;
int[] targetInts = findTargets(targetPoint);
int[] startInts = findTargets(startPoint);
BuildTrackExplorer explorer = new BuildTrackExplorer(world,
principal, startPoint, targetPoint);
explorer.setBuildTrackStrategy(bts);
pathFinder.setupSearch(startInts, targetInts, explorer);
}
}

VerifyStationName

Full name: jfreerails.controller.VerifyStationName

Documentation

/**
* Class to verify that the chosen name for a station hasn't already been taken
* by another station. If the name has been used, a minor alteration in the name
* is required, by adding perhaps "Junction" or "Siding" to the name.
*
* @author Scott Bennett
*
* Date: 12th April 2003
*
*/

Source Code

/**
* Class to verify that the chosen name for a station hasn't already been taken
* by another station. If the name has been used, a minor alteration in the name
* is required, by adding perhaps "Junction" or "Siding" to the name.
*
* @author Scott Bennett
*
* Date: 12th April 2003
*
*/
public class VerifyStationName {
private final ReadOnlyWorld w;
private final String nameToVerify;
private final Vector<String> stationAlternatives;
public VerifyStationName(ReadOnlyWorld world, String name) {
this.w = world;
this.nameToVerify = name;
this.stationAlternatives = new Vector<String>();
stationAlternatives.addElement("Junction");
stationAlternatives.addElement("Siding");
stationAlternatives.addElement("North");
stationAlternatives.addElement("East");
stationAlternatives.addElement("South");
stationAlternatives.addElement("West");
}
public String getName() {
String appropriateName = nameToVerify;
boolean found = false;
String tempName = null;
// if (w.size(KEY.STATIONS) <= 0) {
// //if there are no stations, then obviously the name isn't taken
// return appropriateName;
// }
found = checkStationExists(appropriateName);
if (!found) {
return appropriateName;
}
// a station with that name already exists, so we need to find another
// name
for (int i = 0; i < stationAlternatives.size(); i++) {
tempName = appropriateName + " " + stationAlternatives.elementAt(i);
found = checkStationExists(tempName);
if (!found) {
return tempName;
}
}
int j = 7; // for number of names that have already been used
while (found) {
j++;
tempName = appropriateName + "Station #" + j;
found = checkStationExists(tempName);
}
return tempName;
}
private boolean checkStationExists(String name) {
String testName = name;
StationModel tempStation;
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
while (wi.next()) { // loop over non null stations
tempStation = (StationModel) wi.getElement();
if ((testName).equals(tempStation.getStationName())) {
// station already exists with that name
return true;
}
}
}
// no stations exist with that name
return false;
}
}

PathNotFoundException

Full name: jfreerails.controller.PathNotFoundException

Documentation

/**
* Thrown when a path cannot be found.
*
* @author Luke
*
*/

Source Code

/**
* Thrown when a path cannot be found.
*
* @author Luke
*
*/
public class PathNotFoundException extends Exception {
private static final long serialVersionUID = 4121409601112717368L;
public PathNotFoundException(String arg0) {
super(arg0);
}
}

Message2Server

Full name: jfreerails.controller.Message2Server

Documentation

/**
* Defines a command sent from a client to the server.
*
* @author Luke
*
*/

Source Code

/**
* Defines a command sent from a client to the server.
*
* @author Luke
*
*/
public interface Message2Server extends FreerailsSerializable {
int getID();
MessageStatus execute(ServerControlInterface server);
}

Methods

StationBuilder

Full name: jfreerails.controller.StationBuilder

Documentation

/**
* Class to build a station at a given point, names station after nearest city.
* If that name is taken then a "Junction" or "Siding" is added to the name.
*
* @author Luke Lindsay 08-Nov-2002
*
* Updated 12th April 2003 by Scott Bennett to include nearest city names.
*
*/

Source Code

/**
* Class to build a station at a given point, names station after nearest city.
* If that name is taken then a "Junction" or "Siding" is added to the name.
*
* @author Luke Lindsay 08-Nov-2002
*
* Updated 12th April 2003 by Scott Bennett to include nearest city names.
*
*/
public class StationBuilder {
private static final Logger logger = Logger.getLogger(StationBuilder.class
.getName());
private int ruleNumber;
private final MoveExecutor executor;
public StationBuilder(MoveExecutor executor) {
this.executor = executor;
TrackRule trackRule;
int i = -1;
ReadOnlyWorld world = executor.getWorld();
do {
i++;
trackRule = (TrackRule) world.get(SKEY.TRACK_RULES, i);
} while (!trackRule.isStation());
ruleNumber = i;
}
public MoveStatus tryBuildingStation(ImPoint p) {
ReadOnlyWorld world = executor.getWorld();
FreerailsPrincipal principal = executor.getPrincipal();
AddStationPreMove preMove = AddStationPreMove.newStation(p,
this.ruleNumber, principal);
Move m = preMove.generateMove(world);
MoveStatus ms = executor.tryDoMove(m);
return ms;
}
public MoveStatus buildStation(ImPoint p) {
// Only build a station if there is track at the specified point.
MoveStatus status = tryBuildingStation(p);
if (status.ok) {
FreerailsPrincipal principal = executor.getPrincipal();
AddStationPreMove preMove = AddStationPreMove.newStation(p,
this.ruleNumber, principal);
return executor.doPreMove(preMove);
}
logger.fine(status.message);
return status;
}
public void setStationType(int ruleNumber) {
this.ruleNumber = ruleNumber;
}
public int getTrackTypeID(String string) {
ReadOnlyWorld w = executor.getWorld();
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule r = (TrackRule) w.get(SKEY.TRACK_RULES, i);
if (string.equals(r.getTypeName())) {
return i;
}
}
throw new NoSuchElementException();
}
}

NetWorthCalculator

Full name: jfreerails.controller.NetWorthCalculator

Documentation

/**
* A TransactionAggregator that calculates the networth of a player by
* totalling the value of their assets.
*
* @author Luke
*
*/

Source Code

/**
* A TransactionAggregator that calculates the networth of a player by
* totalling the value of their assets.
*
* @author Luke
*
*/
public class NetWorthCalculator extends TransactionAggregator {
public NetWorthCalculator(ReadOnlyWorld w, FreerailsPrincipal principal) {
super(w, principal);
}
@Override
protected boolean condition(int transactionID) {
Transaction t = super.w.getTransaction(super.principal,
transactionID);
if (t instanceof AddItemTransaction) {
if(t.getCategory().equals(Transaction.Category.ISSUE_STOCK)){
return true;
}
// Since buying something is just converting one asset type to
// another.
return false;
}
return true;
}
}

FlatTrackExplorer

Full name: jfreerails.controller.FlatTrackExplorer

Documentation

/**
* GraphExplorer that explorers track, the ints it returns are encoded
* PositionOnTrack objects.
*
* @author Luke
*/

Source Code

/**
* GraphExplorer that explorers track, the ints it returns are encoded
* PositionOnTrack objects.
*
* @author Luke
*/
public class FlatTrackExplorer implements GraphExplorer, Serializable {
private static final long serialVersionUID = 3834311713465185081L;
private PositionOnTrack currentPosition = PositionOnTrack.createComingFrom(
0, 0, Step.NORTH);
final PositionOnTrack currentBranch = PositionOnTrack.createComingFrom(0,
0, Step.NORTH);
private boolean beforeFirst = true;
private final ReadOnlyWorld w;
public ReadOnlyWorld getWorld() {
return w;
}
public void setPosition(int i) {
beforeFirst = true;
currentPosition.setValuesFromInt(i);
}
public int getPosition() {
return this.currentPosition.toInt();
}
public void moveForward() {
if (beforeFirst) {
throw new IllegalStateException();
}
this.setPosition(this.getVertexConnectedByEdge());
}
public void nextEdge() {
if (!hasNextEdge()) {
throw new NoSuchElementException();
}
Step v = this.getFirstVectorToTry();
Point p = new Point(currentPosition.getX(), currentPosition.getY());
FreerailsTile ft = (FreerailsTile)w.getTile(p.x, p.y);
TrackPiece tp = ft.getTrackPiece();
TrackConfiguration conf = tp.getTrackConfiguration();
Step[] vectors = Step.getList();
int i = v.getID();
int loopCounter = 0;
while (!conf.contains(vectors[i].get9bitTemplate())) {
i++;
i = i % 8;
loopCounter++;
if (8 < loopCounter) {
throw new IllegalStateException();
// This should never happen.. ..but it does happen when you
// removed the track from under a train.
}
}
Step branchDirection = Step.getInstance(i);
this.currentBranch.setCameFrom(branchDirection);
int x = this.currentPosition.getX() + branchDirection.deltaX;
int y = this.currentPosition.getY() + branchDirection.deltaY;
this.currentBranch.setX(x);
this.currentBranch.setY(y);
beforeFirst = false;
}
public int getVertexConnectedByEdge() {
return currentBranch.toInt();
}
public int getEdgeCost() {
return (int) Math.round(currentBranch.cameFrom().getLength());
}
public boolean hasNextEdge() {
if (beforeFirst) {
// We can always go back the way we have come, so if we are before
// the first
// branch, there must be a branch: the one we used to get here.
return true;
}
// Since we can always go back the way we have come, if the direction of
// current branch is not equal to the opposite of the current direction,
// there must be another branch.
Step currentBranchDirection = this.currentBranch.cameFrom();
Step oppositeToCurrentDirection = this.currentPosition.cameFrom()
.getOpposite();
if (oppositeToCurrentDirection.getID() == currentBranchDirection
.getID()) {
return false;
}
return true;
}
public FlatTrackExplorer(ReadOnlyWorld world, PositionOnTrack p) {
w = world;
FreerailsTile tile = (FreerailsTile) world.getTile(p.getX(), p.getY());
if (tile.getTrackPiece().getTrackTypeID() == NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
throw new IllegalArgumentException(p.toString());
}
this.currentPosition = PositionOnTrack.createComingFrom(p.getX(), p
.getY(), p.cameFrom());
}
/**
* @return an array of PositionOnTrack objects describing the set of
* possible orientations at this position (heading towards the
* center of the tile)
* @param p
* location of track to consider.
*/
public static PositionOnTrack[] getPossiblePositions(ReadOnlyWorld w,
ImPoint p) {
TrackPiece tp = ((FreerailsTile) w.getTile(p.x, p.y)).getTrackPiece();
TrackConfiguration conf = tp.getTrackConfiguration();
Step[] vectors = Step.getList();
// Count the number of possible positions.
int n = 0;
for (int i = 0; i < vectors.length; i++) {
if (conf.contains(vectors[i].get9bitTemplate())) {
n++;
}
}
PositionOnTrack[] possiblePositions = new PositionOnTrack[n];
n = 0;
for (int i = 0; i < vectors.length; i++) {
if (conf.contains(vectors[i].get9bitTemplate())) {
possiblePositions[n] = PositionOnTrack.createComingFrom(p.x,
p.y, vectors[i].getOpposite());
n++;
}
}
return possiblePositions;
}
Step getFirstVectorToTry() {
if (beforeFirst) {
// Return the vector that is 45 degrees clockwise from the opposite
// of the current position.
Step v = this.currentPosition.cameFrom();
v = v.getOpposite();
int i = v.getID();
i++;
i = i % 8;
v = Step.getInstance(i);
return v;
}
// Return the vector that is 45 degrees clockwise from the direction
// of the current branch.
Step v = this.currentBranch.cameFrom();
int i = v.getID();
i++;
i = i % 8;
v = Step.getInstance(i);
return v;
}
public int getH() {
// TODO Auto-generated method stub
return 0;
}
}

ReportBugTextGenerator

Full name: jfreerails.controller.ReportBugTextGenerator

Documentation

/**
* Generates text for bug reports, including instructions and exception details.
* This class provides methods to generate bug report text for both general and exception scenarios.
* It also handles unexpected exceptions by displaying an error form and exiting the application.
*
* @see UnexpectedExceptionForm
* @see ScreenHandler
*/

Source Code

public class ReportBugTextGenerator {
private static final String TRACKER_URL = "http://sourceforge.net/tracker/?group_id=9495&atid=109495";
public static void main(String[] args) {
Exception e = genException();
System.out.println(genText());
System.out.println(genText(e));
}
private static Exception genException() {
Exception e = new Exception();
return e;
}
public static String genText() {
StringBuffer sb = new StringBuffer();
sb.append("How to report a bug\n");
sb.append("\n");
sb.append("Use the sourceforge.net bug tracker at the following url:\n");
sb.append(TRACKER_URL);
sb.append("\n");
sb.append("\n");
sb.append("Please include:\n");
sb.append(" 1. Steps to reproduce the bug (attach a save game if appropriate).\n");
sb.append(" 2. What you expected to see.\n");
sb.append(" 3. What you saw instead (attach a screenshot if appropriate).\n");
sb.append(" 4. The details below (copy and past them into the bug report).\n");
appendBuildProps(sb);
sb.append("\n");
sb.append("\n");
return sb.toString();
}
public static String genText(Exception e) {
StackTraceElement[] s = e.getStackTrace();
StringBuffer sb = new StringBuffer();
sb.append("Unexpected Exception\n");
sb.append("\n");
sb.append("Consider submitting a bug report using the sourceforge.net" +
" bug tracker at the following url:\n");
sb.append(TRACKER_URL);
sb.append("\n");
sb.append("\n");
sb.append("Please:\n");
sb.append(" 1. Use the following as the title of the bug report:\n\t");
sb.append(" Unexpected Exception: ");
sb.append(s[0].getFileName());
sb.append(" line ");
sb.append(s[0].getLineNumber());
sb.append("\n");
sb.append(" 2. Include steps to reproduce the bug (attach a save game if appropriate).\n");
sb.append(" 3. Copy and paste the details below into the bug report:\n");
appendBuildProps(sb);
sb.append("\n");
sb.append("\n\t");
sb.append(e.toString());
for (StackTraceElement ste : s) {
sb.append("\n\t\t at ");
sb.append(ste);
}
return sb.toString();
}
private static void appendBuildProps(StringBuffer sb) {
String version = null;
String builtBy = null;;
try {
Properties props = new Properties();
InputStream in = ReportBugTextGenerator.class
.getResourceAsStream("/build.properties");
props.load(in);
in.close();
version = props.getProperty("freerails.build");
builtBy = props.getProperty("freerails.built.by");
} catch (Exception e) {
// ignore, there's nothing useful we can do.
}
version = null == version ? "not set" : version;
builtBy = null == builtBy ? "not set" : builtBy;
sb.append("\t");
sb.append(System.getProperty("os.name"));
sb.append(" ");
sb.append(System.getProperty("os.version"));
sb.append("\n\t");
sb.append(System.getProperty("java.vm.name"));
sb.append(" ");
sb.append(System.getProperty("java.version"));
sb.append("\n\t");
sb.append("Freerails build ");
sb.append(version);
sb.append(" compiled by ");
sb.append(builtBy);
}
@SuppressWarnings("deprecation")
public static void unexpectedException(Exception e) {
ScreenHandler.exitFullScreenMode();
String str = genText(e);
System.err.print(str);
UnexpectedExceptionForm unexpectedExceptionForm = new UnexpectedExceptionForm();
unexpectedExceptionForm.setText(str);
unexpectedExceptionForm.setVisible(true);
if(!EventQueue.isDispatchThread()){
Thread.currentThread().stop();
}
}
}

SharePriceCalculator

Full name: jfreerails.controller.SharePriceCalculator

Documentation

/**
* @author Luke
*
*/

Source Code

/**
* @author Luke
*
*/
public class SharePriceCalculator {
public int totalShares;
public int treasuryStock;
public int otherRRStakes;
public long profitsLastYear;
public long networth;
public long stockholderEquity;
public long calculatePrice() {
assert totalShares > 0;
assert totalShares >= treasuryStock + otherRRStakes;
assert stockholderEquity > 0;
long price;
long currentValue = networth + stockholderEquity;
long expectedIncrease = profitsLastYear * 5;
int publicOwnedShares = totalShares - treasuryStock - otherRRStakes;
price = 2 * (currentValue + expectedIncrease)
/ (2 * publicOwnedShares + otherRRStakes);
return price;
}
}

Methods

CopyableTextJPanel

Full name: jfreerails.controller.CopyableTextJPanel

Documentation

/**
* Displays text that can be selected with the mouse and copied to the clipboard.
*
* @author Luke
*/

Source Code

/**
* Displays text that can be selected with the mouse and copied to the clipboard.
*
* @author Luke
*/
public class CopyableTextJPanel extends javax.swing.JPanel {
private static final long serialVersionUID = 4076159955353400345L;
/** Creates new form CopyableTextJPanel */
public CopyableTextJPanel() {
initComponents();
}
public void setText(String s){
this.jTextArea1.setText(s);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jPopupMenu1 = new javax.swing.JPopupMenu();
copyItem = new javax.swing.JMenuItem();
selectAllItem = new javax.swing.JMenuItem();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
copyItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
copyItem.setText("Copy");
copyItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
copyItemActionPerformed(evt);
}
});
jPopupMenu1.add(copyItem);
selectAllItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
selectAllItem.setText("Select All");
selectAllItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectAllItemActionPerformed(evt);
}
});
jPopupMenu1.add(selectAllItem);
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(500, 300));
jTextArea1.setEditable(false);
jTextArea1.setText("dsfasd\n\nsad\nf\nasd\nfa\nsdf\nas\ndf\nas\ndf\nads\nf\nasd\nf\nads\nf\ndsa\nf\ndsa\nf\ndasf\na\ndsf\nads\nf\nasd\nf\nasd\nf\n\nasdf");
jTextArea1.setWrapStyleWord(true);
jTextArea1.setOpaque(false);
jTextArea1.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTextArea1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTextArea1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}
// </editor-fold>//GEN-END:initComponents
private void selectAllItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectAllItemActionPerformed
jTextArea1.selectAll();
}//GEN-LAST:event_selectAllItemActionPerformed
private void copyItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_copyItemActionPerformed
jTextArea1.copy();
}//GEN-LAST:event_copyItemActionPerformed
private void jTextArea1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextArea1MouseClicked
if(SwingUtilities.isRightMouseButton(evt)){
jPopupMenu1.show(jTextArea1, evt.getX(), evt.getY());
}
}//GEN-LAST:event_jTextArea1MouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JMenuItem copyItem;
javax.swing.JPopupMenu jPopupMenu1;
javax.swing.JScrollPane jScrollPane1;
javax.swing.JTextArea jTextArea1;
javax.swing.JMenuItem selectAllItem;
// End of variables declaration//GEN-END:variables
}

PathOnTrackFinder

Full name: jfreerails.controller.PathOnTrackFinder

Documentation

/**
* Finds a path along existing track. Used for upgrading or removing track
* between two points on the track.
*
* @author Luke
*
*/

Source Code

/**
* Finds a path along existing track. Used for upgrading or removing track
* between two points on the track.
*
* @author Luke
*
*/
public class PathOnTrackFinder implements IncrementalPathFinder {
private static final Logger logger = Logger
.getLogger(IncrementalPathFinder.class.getName());
private SimpleAStarPathFinder pathFinder = new SimpleAStarPathFinder();
private ImPoint startPoint;
private final ReadOnlyWorld world;
public PathOnTrackFinder(ReadOnlyWorld world) {
this.world = world;
}
public void abandonSearch() {
pathFinder.abandonSearch();
}
public int getStatus() {
return pathFinder.getStatus();
}
public Step[] pathAsVectors() {
int[] pathAsInts = pathFinder.retrievePath().toArray();
Step[] vectors = new Step[pathAsInts.length];
int x = startPoint.x;
int y = startPoint.y;
for (int i = 0; i < pathAsInts.length; i++) {
PositionOnTrack p2 = new PositionOnTrack(pathAsInts[i]);
vectors[i] = Step.getInstance(p2.getX() - x, p2.getY() - y);
x = p2.getX();
y = p2.getY();
}
return vectors;
}
public void search(long maxDuration) throws PathNotFoundException {
pathFinder.search(maxDuration);
}
public void setupSearch(ImPoint from, ImPoint target) throws PathNotFoundException {
startPoint = from;
logger
.fine("Find track path from " + from + " to "
+ target);
/* Check there is track at both the points. */
FreerailsTile tileA = (FreerailsTile) world.getTile(from.x,
from.y);
FreerailsTile tileB = (FreerailsTile) world.getTile(target.x,
target.y);
if (!tileA.hasTrack()) {
throw new PathNotFoundException("No track at " + from.x
+ ", " + from.y + ".");
}
if (!tileB.hasTrack()) {
throw new PathNotFoundException("No track at " + target.x
+ ", " + target.y + ".");
}
PositionOnTrack[] startPoints = FlatTrackExplorer.getPossiblePositions(
world, from);
PositionOnTrack[] targetPoints = FlatTrackExplorer
.getPossiblePositions(world, target);
FlatTrackExplorer explorer = new FlatTrackExplorer(world,
startPoints[0]);
pathFinder.setupSearch(PositionOnTrack.toInts(startPoints),
PositionOnTrack.toInts(targetPoints), explorer);
}
}

CalcNearestCity

Full name: jfreerails.controller.CalcNearestCity

Documentation

/**
*
*
* Class to find the nearest city and return that name, so that a station can be
* named appropriately. Date: 12th April 2003
*
* @author Scott Bennett
*/

Source Code

/**
*
*
* Class to find the nearest city and return that name, so that a station can be
* named appropriately. Date: 12th April 2003
*
* @author Scott Bennett
*/
public class CalcNearestCity {
private final int x;
private final int y;
private final ReadOnlyWorld w;
public CalcNearestCity(ReadOnlyWorld world, int x, int y) {
this.w = world;
this.x = x;
this.y = y;
}
public String findNearestCity() {
double cityDistance;
String cityName = null;
double tempDistance;
CityModel tempCity;
if (w.size(SKEY.CITIES) > 0) {
tempCity = (CityModel) w.get(SKEY.CITIES, 0);
cityDistance = getDistance(tempCity.getCityX(), tempCity.getCityY());
cityName = tempCity.getCityName();
for (int i = 1; i < w.size(SKEY.CITIES); i++) {
tempCity = (CityModel) w.get(SKEY.CITIES, i);
tempDistance = getDistance(tempCity.getCityX(), tempCity
.getCityY());
if (tempDistance < cityDistance) {
cityDistance = tempDistance;
cityName = tempCity.getCityName();
}
}
return cityName;
}
throw new NoSuchElementException();
}
private double getDistance(int cityX, int cityY) {
double distance = 0;
double a = (this.x - cityX) * (this.x - cityX);
double b = (this.y - cityY) * (this.y - cityY);
distance = Math.sqrt(a + b);
return distance;
}
}

BalanceSheetGenerator

Full name: jfreerails.controller.BalanceSheetGenerator

Documentation

/**
* Generates the balance sheet - note, its fields are read using reflection so
* don't change their names.
*
* @author Luke
*
*/

Source Code

/**
* Generates the balance sheet - note, its fields are read using reflection so
* don't change their names.
*
* @author Luke
*
*/
public class BalanceSheetGenerator {
GameTime from;
GameTime to;
final ReadOnlyWorld w;
final FreerailsPrincipal principal;
private GameCalendar cal;
public String year;
public Stats total;
public Stats ytd;
public BalanceSheetGenerator(ReadOnlyWorld w, FreerailsPrincipal principal) {
this.w = w;
this.principal = principal;
cal = (GameCalendar) w.get(ITEM.CALENDAR);
// Calculate totals
GameTime time = w.currentTime();
final int startyear = cal.getYear(time.getTicks());
year = String.valueOf(startyear);
GameTime startOfYear = new GameTime(cal.getTicks(startyear));
GameTime[] totalTimeInterval = new GameTime[] { GameTime.BIG_BANG,
GameTime.END_OF_THE_WORLD };
total = new Stats(w, principal, totalTimeInterval);
GameTime[] ytdTimeInterval = new GameTime[] { startOfYear,
GameTime.END_OF_THE_WORLD };
ytd = new Stats(w, principal, ytdTimeInterval);
}
public static Money calTrackTotal(Transaction.Category category,
ReadOnlyWorld w, FreerailsPrincipal principal, GameTime startTime) {
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
w, principal);
aggregator.setCategory(TRACK);
long amount = 0;
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
long trackValue = trackRule.getPrice().getAmount();
GameTime[] times = new GameTime[] { startTime,
GameTime.END_OF_THE_WORLD };
aggregator.setType(i);
aggregator.setTimes(times);
ItemsTransactionAggregator.QuantitiesAndValues qnv = aggregator
.calculateQuantitiesAndValues();
int quantity = qnv.quantities[0];
amount += trackValue * quantity
/ TrackConfiguration.LENGTH_OF_STRAIGHT_TRACK_PIECE;
}
return new Money(amount);
}
public static class Stats {
public Stats(ReadOnlyWorld w, FreerailsPrincipal principal, final GameTime[] totalTimeInterval){
TransactionAggregator operatingFundsAggregator = new TransactionAggregator(w,
principal) {
@Override
protected boolean condition(int i) {
int transactionTicks = w.getTransactionTimeStamp(
principal, i).getTicks();
int from = totalTimeInterval[0].getTicks();
int to = totalTimeInterval[1].getTicks();
return transactionTicks >= from && transactionTicks <=to;
}
};
operatingFunds= operatingFundsAggregator.calculateValue();
track = calTrackTotal(TRACK, w, principal, totalTimeInterval[0]);
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
w, principal);
aggregator.setTimes(totalTimeInterval);
aggregator.setCategory(STATIONS);
stations = aggregator.calculateValue();
aggregator.setCategory(TRAIN);
rollingStock = aggregator.calculateValue();
aggregator.setCategory(INDUSTRIES);
industries = aggregator.calculateValue();
aggregator.setCategory(BOND);
loans = aggregator.calculateValue();
aggregator.setCategory(ISSUE_STOCK);
equity= aggregator.calculateValue();
//If we don't initialize this variable
//we get a NPE when we don't own any stock in others RRs
otherRrStock = new Money(0);
int thisPlayerId = w.getID(principal);
StockPrice[] stockPrices = (new StockPriceCalculator(w)).calculate();
for (int playerId = 0; playerId < w.getNumberOfPlayers(); playerId++) {
aggregator.setCategory(TRANSFER_STOCK);
aggregator.setType(thisPlayerId);
int quantity = aggregator.calculateQuantity();
if (playerId == thisPlayerId) {
treasuryStock = new Money(quantity
* stockPrices[playerId].currentPrice.getAmount());
} else {
otherRrStock = new Money(quantity
* stockPrices[playerId].currentPrice.getAmount()
+ otherRrStock.getAmount());
}
}
calProfit();
}
public Money operatingFunds;
public Money track;
public Money stations;
public Money rollingStock;
public Money industries;
public Money loans;
public Money equity;
public Money treasuryStock;
public Money otherRrStock;
public Money profit;
private void calProfit(){
long profitValue = operatingFunds.getAmount() + track.getAmount()
+ stations.getAmount() + rollingStock.getAmount()
+ industries.getAmount() + loans.getAmount()
+ equity.getAmount() + treasuryStock.getAmount()
+ otherRrStock.getAmount();
profit= new Money(profitValue);
}
}
}

ToAndFroPathIterator

Full name: jfreerails.controller.ToAndFroPathIterator

Documentation

/**
* Returns a path that goes forwards and backwards along the path passed to its
* constructor.
*
* @author Luke Lindsay 30-Oct-2002
*
*/

Source Code

/**
* Returns a path that goes forwards and backwards along the path passed to its
* constructor.
*
* @author Luke Lindsay 30-Oct-2002
*
*/
public class ToAndFroPathIterator implements FreerailsPathIterator {
private static final long serialVersionUID = 3256442525337202993L;
private FreerailsPathIterator path;
private boolean forwards = true;
private final List<Point> list;
public ToAndFroPathIterator(List<Point> l) {
list = l;
nextIterator();
}
private void nextIterator() {
path = new FreerailsPathIteratorImpl(list, forwards);
}
public boolean hasNext() {
if (list.size() < 2) {
return false;
}
return true;
}
public void nextSegment(IntLine line) {
if (this.hasNext()) {
if (!path.hasNext()) {
forwards = !forwards;
path = new FreerailsPathIteratorImpl(list, forwards);
}
path.nextSegment(line);
} else {
throw new NoSuchElementException();
}
}
}

TrainStopsHandler

Full name: jfreerails.controller.TrainStopsHandler

Documentation

/**
* @author Luke
*
*/

Source Code

/**
* @author Luke
*
*/
public class TrainStopsHandler implements Serializable {
private static final Logger logger = Logger.getLogger(TrainStopsHandler.class.getName());
private static final int NOT_AT_STATION = -1;
private static final long serialVersionUID = 3257567287094882872L;
/** If wagons are added to a train, we need to increase its length.*/
static PathOnTiles lengthenPath(ReadOnlyWorld w, PathOnTiles path, int currentTrainLength) {
double pathDistance = path.getTotalDistance();
double extraDistanceNeeded = currentTrainLength - pathDistance;
List<Step> steps = new ArrayList<Step>();
ImPoint start = path.getStart();
Step firstStep = path.getStep(0);
PositionOnTrack nextPot = PositionOnTrack.createComingFrom(start.x, start.y, firstStep);
while( extraDistanceNeeded > 0){
FlatTrackExplorer fte = new FlatTrackExplorer(w, nextPot);
fte.nextEdge();
nextPot.setValuesFromInt(fte.getVertexConnectedByEdge());
Step cameFrom = nextPot.facing();
steps.add(0, cameFrom);
extraDistanceNeeded -= cameFrom.getLength();
}
//Add existing steps
for (int i = 0; i < path.steps(); i++) {
Step step = path.getStep(i);
steps.add(step);
}
ImPoint newStart = new ImPoint(nextPot.getX(), nextPot.getY());
path = new PathOnTiles(newStart, steps);
return path;
}
private final FreerailsPrincipal principal;
private GameTime timeLoadingFinished = new GameTime(0);
private final int trainId;
private final WorldDiffs worldDiffs;
public TrainStopsHandler(int id, FreerailsPrincipal p, WorldDiffs w) {
trainId = id;
principal = p;
worldDiffs = w;
}
public ImPoint arrivesAtPoint(int x, int y) {
TrainAccessor ta = new TrainAccessor(worldDiffs, principal, trainId);
ImPoint targetPoint = ta.getTarget();
if (x == targetPoint.x && y == targetPoint.y) {
updateTarget();
targetPoint = ta.getTarget();
} else {
int stationNumber = getStationID(x, y);
if (NOT_AT_STATION != stationNumber) {
loadAndUnloadCargo(stationNumber, false, false);
}
}
return targetPoint;
}
public Move getMoves() {
Move m = WorldDiffMove.generate(worldDiffs, WorldDiffMove.Cause.TrainArrives);
worldDiffs.reset();
return m;
}
/**
* @return the number of the station the train is currently at, or -1 if no
* current station.
*/
public int getStationID(int x, int y) {
// loop thru the station list to check if train is at the same Point
// as
// a station
for (int i = 0; i < worldDiffs.size(principal, KEY.STATIONS); i++) {
StationModel tempPoint = (StationModel) worldDiffs.get(principal, KEY.STATIONS, i);
if (null != tempPoint && (x == tempPoint.x) && (y == tempPoint.y)) {
return i; // train is at the station at location tempPoint
}
}
return -1;
// there are no stations that exist where the train is currently
}
public int getTrainLength() {
TrainAccessor ta = new TrainAccessor(worldDiffs, principal, trainId);
return ta.getTrain().getLength();
}
public boolean isTrainFull() {
TrainAccessor train = new TrainAccessor(worldDiffs, principal, trainId);
ImInts spaceAvailable = train.spaceAvailable();
return spaceAvailable.sum() == 0;
}
public boolean isTrainMoving() {
if (refreshWaitingForFullLoad()) {
return false;
}
GameTime time = worldDiffs.currentTime();
return time.getTicks() > this.timeLoadingFinished.getTicks();
}
public boolean isWaiting4FullLoad() {
TrainModel train = (TrainModel) worldDiffs.get(principal, KEY.TRAINS, this.trainId);
int scheduleID = train.getScheduleID();
ImmutableSchedule schedule = (ImmutableSchedule) worldDiffs.get(principal,
KEY.TRAIN_SCHEDULES, scheduleID);
if(schedule.getNumOrders() == 0){
return false;
}
TrainOrdersModel order = schedule.getOrder(schedule.getOrderToGoto());
return !isTrainFull() && order.waitUntilFull;
}
void loadAndUnloadCargo(int stationId, boolean waiting, boolean autoConsist) {
// train is at a station so do the cargo processing
DropOffAndPickupCargoMoveGenerator transfer = new DropOffAndPickupCargoMoveGenerator(
trainId, stationId, worldDiffs, principal, waiting, autoConsist);
Move m = transfer.generateMove();
if(null != m){
MoveStatus ms = m.doMove(worldDiffs, principal);
if (!ms.ok)
throw new IllegalStateException(ms.message);
}
}
void makeTrainWait(int ticks) {
GameTime currentTime = worldDiffs.currentTime();
timeLoadingFinished = new GameTime(currentTime.getTicks() + ticks);
}
public boolean refreshWaitingForFullLoad() {
TrainAccessor ta = new TrainAccessor(worldDiffs, principal, trainId);
ImmutableSchedule schedule = ta.getSchedule();
int stationId = ta.getStationId(Double.MAX_VALUE);
if(stationId<0) throw new IllegalStateException();
//The train's orders may have changed...
final int orderToGoto = schedule.getOrderToGoto();
if(-1 == orderToGoto){
//We end up here if all the orders are deleted.
return false;
}
TrainOrdersModel order = schedule.getOrder(orderToGoto);
//Should we go to another station?
if(stationId != order.stationId){
return false;
}
//Should we change the consist?
ImInts consist = ta.getTrain().getConsist();
if(!consist.equals(order.consist)){
// ..if so, we should change the consist.
int oldLength = ta.getTrain().getLength();
int engineType = ta.getTrain().getEngineType();
TrainModel newTrain = ta.getTrain().getNewInstance(engineType, order.consist);
worldDiffs.set(principal, KEY.TRAINS, trainId, newTrain);
int newLength = newTrain.getLength();
//has the trains length increased?
if(newLength > oldLength){
TrainMotion tm = ta.findCurrentMotion(Double.MAX_VALUE);
PathOnTiles path = tm.getPath();
path = lengthenPath(worldDiffs, path, oldLength);
SpeedTimeAndStatus.TrainActivity status = isWaiting4FullLoad() ? WAITING_FOR_FULL_LOAD : STOPPED_AT_STATION;
TrainMotion nextMotion = new TrainMotion(path, newLength,
0, status);
// Create a new Move object.
Move trainMove = new NextActivityMove(nextMotion, trainId,
principal);
MoveStatus ms = trainMove.doMove(worldDiffs, Player.AUTHORITATIVE);
if(!ms.ok) throw new IllegalStateException(ms.message);
}
}
/* Add any cargo that is waiting. */
loadAndUnloadCargo(schedule.getStationToGoto(), order.waitUntilFull, order.autoConsist);
//Should we stop waiting?
if(!order.waitUntilFull){
updateSchedule();
return false;
}
if (isTrainFull()) {
updateSchedule();
return false;
}
return true;
}
private void scheduledStop() {
TrainModel train = (TrainModel) worldDiffs.get(principal, KEY.TRAINS, this.trainId);
Schedule schedule = (ImmutableSchedule) worldDiffs.get(principal, KEY.TRAIN_SCHEDULES,
train.getScheduleID());
ImInts wagonsToAdd = schedule.getWagonsToAdd();
// Loading and unloading cargo takes time, so we make the train wait for
// a few ticks.
makeTrainWait(50);
boolean autoConsist = schedule.autoConsist();
if (null != wagonsToAdd) {
int engine = train.getEngineType();
Move m = ChangeTrainMove.generateMove(this.trainId, train, engine, wagonsToAdd,
principal);
m.doMove(worldDiffs, principal);
}
updateSchedule();
int stationToGoto = schedule.getStationToGoto();
loadAndUnloadCargo(stationToGoto, true, autoConsist);
}
void updateSchedule() {
TrainModel train = (TrainModel) worldDiffs.get(principal, KEY.TRAINS, this.trainId);
int scheduleID = train.getScheduleID();
ImmutableSchedule currentSchedule = (ImmutableSchedule) worldDiffs.get(principal,
KEY.TRAIN_SCHEDULES, scheduleID);
MutableSchedule schedule = new MutableSchedule(currentSchedule);
StationModel station = null;
TrainOrdersModel order = schedule.getOrder(schedule.getOrderToGoto());
boolean waiting4FullLoad = order.waitUntilFull && !isTrainFull();
if (!waiting4FullLoad) {
schedule.gotoNextStation();
ImmutableSchedule newSchedule = schedule.toImmutableSchedule();
worldDiffs.set(principal, KEY.TRAIN_SCHEDULES, scheduleID, newSchedule);
int stationNumber = schedule.getStationToGoto();
station = (StationModel) worldDiffs.get(principal, KEY.STATIONS, stationNumber);
if (null == station) {
logger.warning("null == station, train " + trainId
+ " doesn't know where to go next!");
}
}
}
/**
* Issues a ChangeTrainScheduleMove to set the train to move to the next
* station.
*/
public void updateTarget() {
scheduledStop();
}
}

AddStationPreMove

Full name: jfreerails.controller.AddStationPreMove

Documentation

/**
* Generates a move that adds or upgrades a station.
*
* @author Luke
*
*/

Source Code

/**
* Generates a move that adds or upgrades a station.
*
* @author Luke
*
*/
public class AddStationPreMove implements PreMove {
private static final long serialVersionUID = 3258131349411148085L;
private final ImPoint p;
private final int ruleNumber;
private final FreerailsPrincipal principal;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof AddStationPreMove))
return false;
final AddStationPreMove addStationPreMove = (AddStationPreMove) o;
if (ruleNumber != addStationPreMove.ruleNumber)
return false;
if (!p.equals(addStationPreMove.p))
return false;
if (!principal.equals(addStationPreMove.principal))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = p.hashCode();
result = 29 * result + ruleNumber;
result = 29 * result + principal.hashCode();
return result;
}
private AddStationPreMove(ImPoint p, int trackRule,
FreerailsPrincipal principal) {
this.p = p;
this.ruleNumber = trackRule;
this.principal = principal;
}
public static AddStationPreMove newStation(ImPoint p, int trackRule,
FreerailsPrincipal principal) {
return new AddStationPreMove(p, trackRule, principal);
}
public static AddStationPreMove upgradeStation(ImPoint p, int trackRule,
FreerailsPrincipal principal) {
return new AddStationPreMove(p, trackRule, principal);
}
public Move generateMove(ReadOnlyWorld world) {
TrackMoveTransactionsGenerator transactionsGenerator = new TrackMoveTransactionsGenerator(
world, principal);
FreerailsTile oldTile = (FreerailsTile) world.getTile(p.x, p.y);
String cityName;
String stationName;
FreerailsTile ft = (FreerailsTile)world.getTile(p.x, p.y);
TrackPiece before = ft.getTrackPiece();
TrackRule trackRule = (TrackRule) world.get(SKEY.TRACK_RULES,
this.ruleNumber);
int owner = ChangeTrackPieceCompositeMove.getOwner(principal, world);
TrackPiece after = new TrackPieceImpl(before.getTrackConfiguration(),
trackRule, owner, ruleNumber);
ChangeTrackPieceMove upgradeTrackMove = new ChangeTrackPieceMove(
before, after, p);
CompositeMove move;
if (!oldTile.getTrackPiece().getTrackRule().isStation()) {
// There isn't already a station here, we need to pick a name and
// add an entry
// to the station list.
CalcNearestCity cNC = new CalcNearestCity(world, p.x, p.y);
try {
cityName = cNC.findNearestCity();
VerifyStationName vSN = new VerifyStationName(world, cityName);
stationName = vSN.getName();
} catch (NoSuchElementException e) {
// there are no cities, this should never happen during a proper
// game. However
// some of the unit tests create stations when there are no
// cities.
stationName = "Central Station #"
+ world.size(principal, KEY.STATIONS);
}
// check the terrain to see if we can build a station on it...
move = AddStationMove.generateMove(world, stationName, p,
upgradeTrackMove, principal);
move = addSupplyAndDemand(move, world);
move = transactionsGenerator.addTransactions(move);
} else {
// Upgrade an existing station.
move = AddStationMove.upgradeStation(upgradeTrackMove);
}
return move;
}
private CompositeMove addSupplyAndDemand(CompositeMove m, ReadOnlyWorld w) {
ImList<Move> moves2 = m.getMoves();
Move[] moves = new Move[moves2.size()];
for (int i = 0; i < moves2.size(); i++) {
moves[i] = moves2.get(i);
}
for (int i = 0; i < moves.length; i++) {
if (moves[i] instanceof AddItemToListMove) {
AddItemToListMove move = (AddItemToListMove) moves[i];
if (move.getKey().equals(KEY.STATIONS)) {
StationModel station = (StationModel) move.getAfter();
CalcCargoSupplyRateAtStation supplyRate;
supplyRate = new CalcCargoSupplyRateAtStation(w, station.x,
station.y, ruleNumber);
StationModel stationAfter = supplyRate
.calculations(station);
moves[i] = new AddItemToListMove(move.getKey(), move
.getIndex(), stationAfter, move.getPrincipal());
}
}
}
return new CompositeMove(moves);
}
}

TrainPathIntIterator

Full name: jfreerails.controller.TrainPathIntIterator

Documentation

/**
* FlatTrackExplorer to FreerailsIntIterator adapter.
*
* @author Luke Lindsay 30-Nov-2002.
*
*/

Source Code

/**
* FlatTrackExplorer to FreerailsIntIterator adapter.
*
* @author Luke Lindsay 30-Nov-2002.
*
*/
public class TrainPathIntIterator implements FreerailsIntIterator {
private final FlatTrackExplorer trackExplorer;
public TrainPathIntIterator(FlatTrackExplorer t) {
trackExplorer = t;
}
public boolean hasNextInt() {
return trackExplorer.hasNextEdge();
}
public int nextInt() {
trackExplorer.nextEdge();
trackExplorer.moveForward();
return trackExplorer.getPosition();
}
}

FreerailsServerSerializable

Full name: jfreerails.controller.FreerailsServerSerializable

Documentation

/**
* Tags classes that the server may need to save but which won't be sent to
* clients.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* Tags classes that the server may need to save but which won't be sent to
* clients.
*
* @author Luke Lindsay
*
*/
public interface FreerailsServerSerializable extends Serializable {
}

Methods

No methods found

BuildTrackStrategy

Full name: jfreerails.controller.BuildTrackStrategy

Documentation

/**
* A BuildTrackStrategy determines which track types to build (or upgrade to) on
* different terrains.
*
* @author Luke
*/

Source Code

/**
* A BuildTrackStrategy determines which track types to build (or upgrade to) on
* different terrains.
*
* @author Luke
*/
public class BuildTrackStrategy {
private final int[] rules;
public static BuildTrackStrategy getSingleRuleInstance(int trackTypeID,
ReadOnlyWorld w) {
int noTerrainTypes = w.size(SKEY.TERRAIN_TYPES);
int[] newRules = new int[noTerrainTypes];
for (int i = 0; i < noTerrainTypes; i++) {
newRules[i] = trackTypeID;
}
return new BuildTrackStrategy(newRules);
}
public static BuildTrackStrategy getMultipleRuleInstance(
ArrayList<Integer> ruleIDs, ReadOnlyWorld w) {
int[] rulesArray = generateRules(ruleIDs, w);
return new BuildTrackStrategy(rulesArray);
}
public static BuildTrackStrategy getDefault(ReadOnlyWorld w) {
ArrayList<Integer> allowable = new ArrayList<Integer>();
allowable.add(getCheapest(TrackRule.TrackCategories.track, w));
allowable.add(getCheapest(TrackRule.TrackCategories.bridge, w));
allowable.add(getCheapest(TrackRule.TrackCategories.tunnel, w));
return new BuildTrackStrategy(generateRules(allowable, w));
}
private static Integer getCheapest(TrackRule.TrackCategories category,
ReadOnlyWorld w) {
TrackRule cheapest = null;
Integer cheapestID = null;
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule rule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
if (rule.getCategory().equals(category)) {
if (null == cheapest
|| cheapest.getPrice().getAmount() > rule.getPrice()
.getAmount()) {
cheapest = rule;
cheapestID = new Integer(i);
}
}
}
return cheapestID;
}
private static int[] generateRules(ArrayList<Integer> allowable,
ReadOnlyWorld w) {
int noTerrainTypes = w.size(SKEY.TERRAIN_TYPES);
int[] newRules = new int[noTerrainTypes];
for (int i = 0; i < noTerrainTypes; i++) {
TerrainType terrainType = (TerrainType) w
.get(SKEY.TERRAIN_TYPES, i);
newRules[i] = -1; // the default value.
for (Integer rule : allowable) {
if (null != rule) {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES,
rule.intValue());
if (trackRule.canBuildOnThisTerrainType(terrainType
.getCategory())) {
newRules[i] = rule.intValue();
break;
}
}
}
}
return newRules;
}
/** Creates a new instance of BuildTrackStrategy */
private BuildTrackStrategy(int[] r) {
rules = r;
}
public int getRule(int terrainType) {
return rules[terrainType];
}
}

MoveTrainPreMove

Full name: jfreerails.controller.MoveTrainPreMove

Documentation

/**
* Generates moves for changes in train position and stops at stations.
*
* @author Luke
*
*/

Source Code

/**
* Generates moves for changes in train position and stops at stations.
*
* @author Luke
*
*/
public class MoveTrainPreMove implements PreMove {
private static final long serialVersionUID = 3545516188269491250L;
private static final Logger logger = Logger.getLogger(MoveTrainPreMove.class
.getName());
/** Uses static method to make testing easier.*/
public static Step findNextStep(ReadOnlyWorld world,
PositionOnTrack currentPosition, ImPoint target) {
PathOnTrackFinder pathFinder = new PathOnTrackFinder(world);
try {
ImPoint location = new ImPoint(currentPosition.getX(),
currentPosition.getY());
pathFinder.setupSearch(location, target);
pathFinder.search(-1);
return pathFinder.pathAsVectors()[0];
} catch (PathNotFoundException e) {
// The pathfinder couldn't find a path so we
// go in any legal direction.
FlatTrackExplorer explorer = new FlatTrackExplorer(world,
currentPosition);
explorer.nextEdge();
int next = explorer.getVertexConnectedByEdge();
PositionOnTrack nextPosition = new PositionOnTrack(next);
return nextPosition.cameFrom();
}
}
private final FreerailsPrincipal principal;
private final int trainID;
public MoveTrainPreMove(int id, FreerailsPrincipal p) {
trainID = id;
principal = p;
}
double acceleration(int wagons) {
return 0.5d/(wagons + 1);
}
/**
* Returns true iff an updated is due.
*
*/
public boolean isUpdateDue(ReadOnlyWorld w) {
GameTime currentTime = w.currentTime();
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
ActivityIterator ai = w.getActivities(principal, trainID);
ai.gotoLastActivity();
double finishTime = ai.getFinishTime();
double ticks = currentTime.getTicks();
boolean hasFinishedLastActivity = Math.floor(finishTime) <= ticks;
TrainActivity trainActivity = ta.getStatus(finishTime);
if(trainActivity == TrainActivity.WAITING_FOR_FULL_LOAD){
//Check whether there is any cargo that can be added to the train.
ImInts spaceAvailable = ta.spaceAvailable();
int stationId = ta.getStationId(ticks);
if(stationId == -1)
throw new IllegalStateException();
StationModel station = (StationModel)w.get(principal, KEY.STATIONS, stationId);
CargoBundle cb = (CargoBundle)w.get(principal, KEY.CARGO_BUNDLES, station.getCargoBundleID());
for(int i = 0; i < spaceAvailable.size(); i++){
int space = spaceAvailable.get(i);
int atStation = cb.getAmount(i);
if(space * atStation > 0){
logger.fine("There is cargo to transfer!");
return true;
}
}
return !ta.keepWaiting();
}
return hasFinishedLastActivity;
}
private ImPoint currentTrainTarget(ReadOnlyWorld w) {
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
return ta.getTarget();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof MoveTrainPreMove))
return false;
final MoveTrainPreMove moveTrainPreMove = (MoveTrainPreMove) o;
if (trainID != moveTrainPreMove.trainID)
return false;
if (!principal.equals(moveTrainPreMove.principal))
return false;
return true;
}
public Move generateMove(ReadOnlyWorld w) {
// Check that we can generate a move.
if (!isUpdateDue(w))
throw new IllegalStateException();
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
TrainMotion tm = ta.findCurrentMotion(Double.MAX_VALUE);
SpeedTimeAndStatus.TrainActivity activity = tm.getActivity();
switch (activity) {
case STOPPED_AT_STATION:
return moveTrain(w);
case READY:
{
// Are we at a station?
TrainStopsHandler stopsHandler = new TrainStopsHandler(trainID,
principal, new WorldDiffs(w));
ta.getStationId(Integer.MAX_VALUE);
PositionOnTrack pot = tm.getFinalPosition();
int x = pot.getX();
int y = pot.getY();
boolean atStation = stopsHandler.getStationID(x, y) >= 0;
TrainMotion nextMotion;
if (atStation) {
// We have just arrived at a station.
double durationOfStationStop = 10;
stopsHandler.arrivesAtPoint(x, y);
SpeedTimeAndStatus.TrainActivity status = stopsHandler.isWaiting4FullLoad() ? WAITING_FOR_FULL_LOAD : STOPPED_AT_STATION;
PathOnTiles path = tm.getPath();
int lastTrainLength = tm.getTrainLength();
int currentTrainLength = stopsHandler.getTrainLength();
//If we are adding wagons we may need to lengthen the path.
if(lastTrainLength < currentTrainLength){
path = TrainStopsHandler.lengthenPath(w, path, currentTrainLength);
}
nextMotion = new TrainMotion(path, currentTrainLength,
durationOfStationStop, status);
// Create a new Move object.
Move trainMove = new NextActivityMove(nextMotion, trainID,
principal);
Move cargoMove = stopsHandler.getMoves();
return new CompositeMove(trainMove, cargoMove);
}
return moveTrain(w);
}
case WAITING_FOR_FULL_LOAD:
{
TrainStopsHandler stopsHandler = new TrainStopsHandler(trainID,
principal, new WorldDiffs(w));
boolean waiting4fullLoad = stopsHandler.refreshWaitingForFullLoad();
Move cargoMove = stopsHandler.getMoves();
if(!waiting4fullLoad){
Move trainMove = moveTrain(w);
if(null != trainMove){
return new CompositeMove(trainMove, cargoMove);
}else{
return cargoMove;
}
}
stopsHandler.makeTrainWait(30);
return cargoMove;
}
default:
throw new UnsupportedOperationException(activity.toString());
}
}
public SpeedTimeAndStatus.TrainActivity getActivity(ReadOnlyWorld w){
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
TrainMotion tm = ta.findCurrentMotion(Integer.MAX_VALUE);
return tm.getActivity();
}
@Override
public int hashCode() {
int result;
result = trainID;
result = 29 * result + principal.hashCode();
return result;
}
private TrainMotion lastMotion(ReadOnlyWorld w) {
ActivityIterator ai = w.getActivities(principal, trainID);
ai.gotoLastActivity();
TrainMotion lastMotion = (TrainMotion) ai.getActivity();
return lastMotion;
}
private Move moveTrain(ReadOnlyWorld w) {
// Find the next vector.
Step nextVector = nextStep(w);
HashMap<TrackSection, Integer> occupiedTrackSections = occupiedTrackSections(w);
TrainMotion motion = lastMotion(w);
PositionOnTrack pot = motion.getFinalPosition();
ImPoint tile = new ImPoint(pot.getX(), pot.getY());
TrackSection desiredTrackSection = new TrackSection(nextVector, tile);
// Check whether the desired track section is single or double track.
ImPoint tileA = desiredTrackSection.tileA();
ImPoint tileB = desiredTrackSection.tileB();
FreerailsTile fta = (FreerailsTile) w.getTile(tileA.x, tileA.y);
FreerailsTile ftb = (FreerailsTile) w.getTile(tileB.x, tileB.y);
TrackPiece tpa = fta.getTrackPiece();
TrackPiece tpb = ftb.getTrackPiece();
int tracks = 1;
if (tpa.getTrackRule().isDouble() && tpb.getTrackRule().isDouble()) {
tracks = 2;
}
if (occupiedTrackSections.containsKey(desiredTrackSection)) {
int trains = occupiedTrackSections.get(desiredTrackSection);
if (trains >= tracks) {
// We need to wait for the track ahead to clear.
return stopTrain(w);
}
}
// Create a new train motion object.
TrainMotion nextMotion = nextMotion(w, nextVector);
return new NextActivityMove(nextMotion, trainID, principal);
}
private HashMap<TrackSection, Integer> occupiedTrackSections(ReadOnlyWorld w) {
HashMap<TrackSection, Integer> occupiedTrackSections = new HashMap<TrackSection, Integer>();
for (int i = 0; i < w.size(principal, KEY.TRAINS); i++) {
TrainModel train = (TrainModel) w.get(principal,
KEY.TRAINS, i);
if (null == train)
continue;
TrainAccessor ta = new TrainAccessor(w, principal, i);
GameTime gt = w.currentTime();
if(ta.isMoving(gt.getTicks())){
HashSet<TrackSection> sections = ta.occupiedTrackSection(gt.getTicks());
for (TrackSection section : sections) {
if(occupiedTrackSections.containsKey(section)){
int count = occupiedTrackSections.get(section);
count++;
occupiedTrackSections.put(section, count);
}else{
occupiedTrackSections.put(section, 1);
}
}
}
}
return occupiedTrackSections;
}
TrainMotion nextMotion(ReadOnlyWorld w, Step v) {
TrainMotion motion = lastMotion(w);
SpeedAgainstTime speeds = nextSpeeds(w, v);
PathOnTiles currentTiles = motion.getTiles(motion.duration());
PathOnTiles pathOnTiles = currentTiles.addSteps(v);
return new TrainMotion(pathOnTiles, currentTiles.steps(), motion
.getTrainLength(), speeds);
}
SpeedAgainstTime nextSpeeds(ReadOnlyWorld w, Step v) {
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
TrainMotion lastMotion = lastMotion(w);
double u = lastMotion.getSpeedAtEnd();
double s = v.getLength();
int wagons = ta.getTrain().getNumberOfWagons();
double a0 = acceleration(wagons);
double topSpeed = topSpeed(wagons);
SpeedAgainstTime newSpeeds;
if (u < topSpeed) {
double t = (topSpeed - u) / a0;
SpeedAgainstTime a = ConstAcc.uat(u, a0, t);
t = s / topSpeed + 1; // Slightly overestimate the time
SpeedAgainstTime b = ConstAcc.uat(topSpeed, 0, t);
newSpeeds = new CompositeSpeedAgainstTime(a, b);
} else {
double t;
t = s / topSpeed + 1; // Slightly overestimate the time
newSpeeds = ConstAcc.uat(topSpeed, 0, t);
}
return newSpeeds;
}
Step nextStep(ReadOnlyWorld w) {
// Find current position.
TrainMotion currentMotion = lastMotion(w);
PositionOnTrack currentPosition = currentMotion.getFinalPosition();
// Find targets
ImPoint targetPoint = currentTrainTarget(w);
return findNextStep(w, currentPosition, targetPoint);
}
public Move stopTrain(ReadOnlyWorld w) {
TrainMotion motion = lastMotion(w);
SpeedAgainstTime stopped = ConstAcc.STOPPED;
double duration = motion.duration();
int trainLength = motion.getTrainLength();
PathOnTiles tiles = motion.getTiles(duration);
int engineDist = tiles.steps();
TrainMotion nextMotion = new TrainMotion(tiles, engineDist,
trainLength, stopped);
return new NextActivityMove(nextMotion, trainID, principal);
}
double topSpeed(int wagons) {
return 10 / (wagons + 1);
}
}

ClientControlInterface

Full name: jfreerails.controller.ClientControlInterface

Documentation

/**
* Defines the methods that the server can call on a client using a
* Message2Client.
*
* @see Message2Client
* @author Luke
*
*/

Source Code

/**
* Defines the methods that the server can call on a client using a
* Message2Client.
*
* @see Message2Client
* @author Luke
*
*/
public interface ClientControlInterface {
public enum ClientProperty {CONNECTED_CLIENTS, MAPS_AVAILABLE, SAVED_GAMES}
/** Called when a new game is started or a game is loaded. */
void setGameModel(FreerailsMutableSerializable world);
/** Sets a property, for example, the list of saved games. */
void setProperty(ClientProperty propertyName, Serializable value);
}

Message2Client

Full name: jfreerails.controller.Message2Client

Documentation

/**
* Defines a command sent from the server to the client.
*
* @author Luke
*
*/

Source Code

/**
* Defines a command sent from the server to the client.
*
* @author Luke
*
*/
public interface Message2Client extends FreerailsSerializable {
/** Executes this command on the specified ClientControlInterface. */
MessageStatus execute(ClientControlInterface client);
/** Returns the id of this command. */
int getID();
}

Methods

GraphExplorer

Full name: jfreerails.controller.GraphExplorer

Documentation

/**
* This interface lets the caller explorer a graph while hiding the way the
* graph is stored. Vertices are packed into single ints to avoid the cost of
* object creation and garbage collection.
*
* 24-Nov-2002
*
* @author Luke Lindsay
*/

Source Code

/**
* This interface lets the caller explorer a graph while hiding the way the
* graph is stored. Vertices are packed into single ints to avoid the cost of
* object creation and garbage collection.
*
* 24-Nov-2002
*
* @author Luke Lindsay
*/
public interface GraphExplorer {
void setPosition(int vertex);
/** Return the current edge. */
int getPosition();
/**
* Sets the current edge to the current vertex's next edge. Throws a
* NoSuchElementException if the vertex does not have another edge.
*/
void nextEdge();
/**
* Returns the vertex that is connected to the current vertex by the current
* edge.
*/
int getVertexConnectedByEdge();
/** Returns the cost of the current edge. */
int getEdgeCost();
boolean hasNextEdge();
/**
* Moves this GraphExplorer from the current vertex to the vertex that is
* connected to the current vertex by the current edge.
*/
void moveForward();
int getH();
}

ModelRoot

Full name: jfreerails.controller.ModelRoot

Documentation

/**
* Defines methods and constants that GUI classes can use to access shared data.
*
* @author Luke
*
*/

Source Code

/**
* Defines methods and constants that GUI classes can use to access shared data.
*
* @author Luke
*
*/
public interface ModelRoot extends MoveExecutor {
public enum Property {
CURSOR_POSITION, CURSOR_MODE, TRACK_BUILDER_MODE, PREVIOUS_CURSOR_MODE, CURSOR_MESSAGE, QUICK_MESSAGE, PERMANENT_MESSAGE, SHOW_STATION_NAMES, SHOW_CARGO_AT_STATIONS, SHOW_STATION_BORDERS, SERVER, PLAY_SOUNDS, BUILD_TRACK_STRATEGY, IGNORE_KEY_EVENTS, PROPOSED_TRACK, SAVED_GAMES_LIST, THINKING_POINT, TIME, SELECTED_TRAIN
}
public enum Value {
PLACE_STATION_CURSOR_MODE, BUILD_TRACK_CURSOR_MODE
}
void sendCommand(Message2Server c);
void setProperty(Property property, Object newValue);
/**
* Tests whether the specified property has the specified value.
*/
boolean is(Property property, Object value);
Object getProperty(Property property);
}

StockPriceCalculator

Full name: jfreerails.controller.StockPriceCalculator

Documentation

/**
* Calculates the stock price for each of the players.
* Stock price = [Net worth + 5 * profit last year] / [ shares owned by public +
0.5 shares owned by other players]
Let profit last year = 100,000 in the first year.
* @author Luke
*
*/

Source Code

/**
* Calculates the stock price for each of the players.
* Stock price = [Net worth + 5 * profit last year] / [ shares owned by public +
0.5 shares owned by other players]
Let profit last year = 100,000 in the first year.
* @author Luke
*
*/
public class StockPriceCalculator {
public static class StockPrice{
public StockPrice(long netWorth, long profitLastyear, int publicShares, int otherRRShares){
currentPrice = calStockPrice(netWorth, profitLastyear, publicShares, otherRRShares);
sellPrice = calStockPrice(netWorth, profitLastyear, publicShares + STOCK_BUNDLE_SIZE, otherRRShares - STOCK_BUNDLE_SIZE);
buyPrice = calStockPrice(netWorth, profitLastyear, publicShares - STOCK_BUNDLE_SIZE, otherRRShares + STOCK_BUNDLE_SIZE);
treasurySellPrice = calStockPrice(netWorth, profitLastyear, publicShares + STOCK_BUNDLE_SIZE, otherRRShares);
treasuryBuyPrice = calStockPrice(netWorth, profitLastyear, publicShares - STOCK_BUNDLE_SIZE, otherRRShares);
}
public Money currentPrice;
public Money sellPrice;
public Money buyPrice;
public Money treasuryBuyPrice;
public Money treasurySellPrice;
}
private final ReadOnlyWorld w;
public StockPriceCalculator(ReadOnlyWorld w){
this.w = w;
}
public StockPrice[] calculate() {
StockPrice[] stockPrices = new StockPrice[w.getNumberOfPlayers()];
for (int playerId = 0; playerId < stockPrices.length; playerId++) {
long profitLastYear;
if(isFirstYear(playerId)){
profitLastYear = 100000;
}else{
profitLastYear = profitsLastYear(playerId);
}
long netWorth = netWorth(playerId);
int publicShares = sharesOwnedByPublic(playerId);
int otherRRShares = sharesOwnedByOtherPlayers(playerId);
stockPrices[playerId] = new StockPrice(netWorth, profitLastYear, publicShares, otherRRShares);
}
return stockPrices;
}
/** Returns true if the current time in the same year as the first transaction for the
* specified player.
*/
boolean isFirstYear(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
GameTime firstTransactionTime = w.getTransactionTimeStamp(pr, 0);
GameCalendar calendar = (GameCalendar)w.get(ITEM.CALENDAR);
int year = calendar.getYear(firstTransactionTime.getTicks());
GameTime currentTime = w.currentTime();
int currentYear = calendar.getYear(currentTime.getTicks());
return year == currentYear;
}
/** Returns the players networth at the start of this year.*/
long netWorth(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
NetWorthCalculator nwc = new NetWorthCalculator(w, pr);
//Set the interval to beginning of time to start of this year.
GameCalendar calendar = (GameCalendar)w.get(ITEM.CALENDAR);
GameTime currentTime = w.currentTime();
int currentYear = calendar.getYear(currentTime.getTicks());
int ticksAtStartOfyear = calendar.getTicks(currentYear);
GameTime[] times = {GameTime.BIG_BANG, new GameTime(ticksAtStartOfyear + 1)};
nwc.setTimes(times);
return nwc.calculateValue().getAmount();
}
long profitsLastYear(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
GameCalendar calendar = (GameCalendar)w.get(ITEM.CALENDAR);
GameTime currentTime = w.currentTime();
int currentYear = calendar.getYear(currentTime.getTicks());
int lastyear = currentYear - 1;
int ticksAtStartOfyear = calendar.getTicks(currentYear);
int ticksAtStartOfLastYear = calendar.getTicks(lastyear);
GameTime[] interval = {new GameTime(ticksAtStartOfLastYear), new GameTime(ticksAtStartOfyear)};
TransactionAggregator aggregator = new TransactionAggregator(w, pr){
@Override
protected boolean condition(int transactionID) {
Transaction t = super.w.getTransaction(super.principal,
transactionID);
if (t instanceof AddItemTransaction) {
// Since buying something is just converting one asset type to
// another.
return false;
}
return true;
}
};
aggregator.setTimes(interval);
return aggregator.calculateValue().getAmount();
}
int sharesOwnedByPublic(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
FinancialDataGatherer gatherer = new FinancialDataGatherer(w, pr);
return gatherer.sharesHeldByPublic();
}
int sharesOwnedByOtherPlayers(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
FinancialDataGatherer gatherer = new FinancialDataGatherer(w, pr);
int[] stakes = gatherer.getStockInThisRRs();
int total = 0;
for (int i = 0; i < stakes.length; i++) {
if(i != playerId){
total+= stakes[i];
}
}
return total;
}
static Money calStockPrice(long netWorth, long profitLastyear, int publicShares, int otherRRShares){
if((publicShares + otherRRShares) == 0 ) return new Money(Long.MAX_VALUE);
long price = 2 * (5 * profitLastyear + netWorth) /(2 * publicShares + otherRRShares);
return new Money(price);
}
}

ProcessCargoAtStationMoveGenerator

Full name: jfreerails.controller.ProcessCargoAtStationMoveGenerator

Documentation

/**
* This class generates Moves that pay the player for delivering the cargo.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* This class generates Moves that pay the player for delivering the cargo.
*
* @author Luke Lindsay
*
*/
public class ProcessCargoAtStationMoveGenerator {
/**
* Determines how much the player gets for delivering cargo. Changed from
* 100 to 75 to fix bug 910132 (Too easy to make money!)
*/
private final static int MAGIC_NUMBER = 75;
public static ArrayList<Move> processCargo(ReadOnlyWorld w,
CargoBundle bundle, int stationID, FreerailsPrincipal p,
int trainId) {
StationModel thisStation = (StationModel) w.get(p,
KEY.STATIONS, stationID);
Iterator<CargoBatch> batches = bundle.cargoBatchIterator();
ArrayList<Move> moves = new ArrayList<Move>();
while (batches.hasNext()) {
CargoBatch batch = batches.next();
double distanceSquared = (batch.getSourceX() - thisStation.x)
* (batch.getSourceX() - thisStation.x)
+ (batch.getSourceY() - thisStation.y)
* (batch.getSourceY() - thisStation.y);
double dist = Math.sqrt(distanceSquared);
int quantity = bundle.getAmount(batch);
double amount = quantity * Math.log(dist) * MAGIC_NUMBER;
Money money = new Money((long) amount);
DeliverCargoReceipt receipt = new DeliverCargoReceipt(money,
quantity, stationID, batch, trainId);
moves.add(new AddTransactionMove(p, receipt));
}
return moves;
}
}

Methods

CalcCargoSupplyRateAtStation

Full name: jfreerails.controller.CalcCargoSupplyRateAtStation

Documentation

/**
* This class probes the tiles adjacent to a station for what cargo they supply,
* demand, and convert and then returns a vector of these rates.
*
* @author Scott Bennett
* @author Luke Created: 9th May 2003
*/

Source Code

/**
* This class probes the tiles adjacent to a station for what cargo they supply,
* demand, and convert and then returns a vector of these rates.
*
* @author Scott Bennett
* @author Luke Created: 9th May 2003
*/
public class CalcCargoSupplyRateAtStation {
private static final Logger logger = Logger
.getLogger(CalcCargoSupplyRateAtStation.class.getName());
/**
* The threshold that demand for a cargo must exceed before the station
* demands the cargo.
*/
private static final int PREREQUISITE_FOR_DEMAND = 16;
private final int[] converts;
private final int[] demand;
private final Vector<CargoElementObject> supplies;
private final ReadOnlyWorld w;
private int x;
private int y;
private int stationRadius;
/**
* Call this constructor if the station does not exist yet.
*
* @param trackRuleNo
* the station type.
*/
public CalcCargoSupplyRateAtStation(ReadOnlyWorld world, int X, int Y,
int trackRuleNo) {
this.w = world;
this.x = X;
this.y = Y;
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, trackRuleNo);
stationRadius = trackRule.getStationRadius();
supplies = new Vector<CargoElementObject>();
populateSuppliesVector();
int numCargoTypes = w.size(SKEY.CARGO_TYPES);
demand = new int[numCargoTypes];
converts = ConvertedAtStation.emptyConversionArray(numCargoTypes);
}
/** Call this constructor if the station already exists. */
public CalcCargoSupplyRateAtStation(ReadOnlyWorld world, int X, int Y) {
this(world, X, Y, findTrackRule(X, Y, world));
}
public ConvertedAtStation getConversion() {
return new ConvertedAtStation(this.converts);
}
public Demand4Cargo getDemand() {
boolean[] demandboolean = new boolean[w.size(SKEY.CARGO_TYPES)];
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
if (demand[i] >= PREREQUISITE_FOR_DEMAND) {
demandboolean[i] = true;
}
}
return new Demand4Cargo(demandboolean);
}
private void incrementSupplyAndDemand(int i, int j) {
int tileTypeNumber = ((FreerailsTile) w.getTile(i, j))
.getTerrainTypeID();
TerrainType terrainType = (TerrainType) w.get(SKEY.TERRAIN_TYPES,
tileTypeNumber);
// Calculate supply.
ImList<Production> production = terrainType.getProduction();
// loop through the production array and increment
// the supply rates for the station
for (int m = 0; m < production.size(); m++) {
int type = production.get(m).getCargoType();
int rate = production.get(m).getRate();
// loop through supplies vector and increment the cargo values as
// required
updateSupplyRate(type, rate);
}
// Now calculate demand.
ImList<Consumption> consumption = terrainType.getConsumption();
for (int m = 0; m < consumption.size(); m++) {
int type = consumption.get(m).getCargoType();
int prerequisite = consumption.get(m).getPrerequisite();
// The prerequisite is the number tiles of this type that must
// be within the station radius before the station demands the
// cargo.
demand[type] += PREREQUISITE_FOR_DEMAND / prerequisite;
}
ImList<Conversion> conversion = terrainType.getConversion();
for (int m = 0; m < conversion.size(); m++) {
int type = conversion.get(m).getInput();
// Only one tile that converts the cargo type is needed for the
// station to demand the cargo type.
demand[type] += PREREQUISITE_FOR_DEMAND;
converts[type] = conversion.get(m).getOutput();
}
}
private void populateSuppliesVector() {
// fill supplies vector with 0 values for all cargo types
// get the correct list of cargoes from the world object
CargoElementObject tempCargoElement;
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
// cT = (CargoType) w.get(SKEY.CARGO_TYPES, i);
tempCargoElement = new CargoElementObject(0, i);
supplies.add(tempCargoElement);
}
}
public Vector<CargoElementObject> scanAdjacentTiles() {
int stationDiameter = stationRadius * 2 + 1;
Rectangle stationRadiusRect = new Rectangle(x - stationRadius, y
- stationRadius, stationDiameter, stationDiameter);
Rectangle mapRect = new Rectangle(0, 0, w.getMapWidth(), w
.getMapHeight());
Rectangle tiles2scan = stationRadiusRect.intersection(mapRect);
logger.fine("stationRadiusRect=" + stationRadiusRect);
logger.fine("mapRect=" + mapRect);
logger.fine("tiles2scan=" + tiles2scan);
// Look at the terrain type of each tile and retrieve the cargo
// supplied.
// The station radius determines how many tiles each side we look at.
for (int i = tiles2scan.x; i < (tiles2scan.x + tiles2scan.width); i++) {
for (int j = tiles2scan.y; j < (tiles2scan.y + tiles2scan.height); j++) {
incrementSupplyAndDemand(i, j);
}
}
// return the supplied cargo rates
return supplies;
}
private static int findTrackRule(int xx, int yy, ReadOnlyWorld w) {
FreerailsTile tile = (FreerailsTile) w.getTile(xx, yy);
int ruleNumber = tile.getTrackPiece().getTrackTypeID();
return ruleNumber;
}
private void updateSupplyRate(int type, int rate) {
// loop through supplies vector and increment the cargo values as
// required
for (int n = 0; n < supplies.size(); n++) {
CargoElementObject tempElement = supplies.elementAt(n);
if (tempElement.getType() == type) {
// cargo types are the same, so increment the rate in supply
// with the rate.
tempElement.setRate(tempElement.getRate() + rate);
break; // no need to go through the rest if we've found a match
}
}
}
/**
*
* Process each existing station, updating what is supplied to it.
*
* @param station
* A StationModel object to be processed
*
*/
public StationModel calculations(StationModel station) {
int[] cargoSupplied = new int[w.size(SKEY.CARGO_TYPES)];
Vector<CargoElementObject> supply = scanAdjacentTiles();
// grab the supply rates from the vector
for (int i = 0; i < supply.size(); i++) {
cargoSupplied[i] = supply.get(i).getRate();
}
// set the supply rates for the current station
SupplyAtStation supplyAtStation = new SupplyAtStation(cargoSupplied);
station = new StationModel(station, supplyAtStation);
station = new StationModel(station, getDemand());
station = new StationModel(station, getConversion());
return station;
}
}

RandomPathFinder

Full name: jfreerails.controller.RandomPathFinder

Documentation

/**
* Returns a random path along the track.
*
* @author Luke Lindsay 13-Oct-2002
*
*/

Source Code

/**
* Returns a random path along the track.
*
* @author Luke Lindsay 13-Oct-2002
*
*/
public class RandomPathFinder implements FreerailsPathIterator {
private static final long serialVersionUID = 3832906571880608313L;
private final FlatTrackExplorer trackExplorer;
private final PositionOnTrack p1 = new PositionOnTrack();
private final PositionOnTrack p2 = new PositionOnTrack();
private static final int tileSize = 30;
public RandomPathFinder(FlatTrackExplorer tx) {
trackExplorer = tx;
}
public boolean hasNext() {
return trackExplorer.hasNextEdge();
}
public void nextSegment(IntLine line) {
p1.setValuesFromInt(trackExplorer.getPosition());
line.x1 = p1.getX() * tileSize + tileSize / 2;
line.y1 = p1.getY() * tileSize + tileSize / 2;
trackExplorer.nextEdge();
trackExplorer.moveForward();
p2.setValuesFromInt(trackExplorer.getPosition());
line.x2 = p2.getX() * tileSize + tileSize / 2;
line.y2 = p2.getY() * tileSize + tileSize / 2;
}
}

BuildTrackExplorer

Full name: jfreerails.controller.BuildTrackExplorer

Documentation

/**
* GraphExplorer that explorers possible track placements, the ints it returns
* are encoded PositionOnTrack objects.
*
* @author Luke
*
*/

Source Code

/**
* GraphExplorer that explorers possible track placements, the ints it returns
* are encoded PositionOnTrack objects.
*
* @author Luke
*
*/
public class BuildTrackExplorer implements GraphExplorer {
private static final TrackConfiguration TILE_CENTER = TrackConfiguration
.getFlatInstance("000010000");
private boolean beforeFirst = true;
final PositionOnTrack currentBranch = PositionOnTrack.createComingFrom(0,
0, Step.NORTH);
final private PositionOnTrack currentPosition = PositionOnTrack
.createComingFrom(0, 0, Step.NORTH);
private int directionInt = 0;
private final ImPoint target;
private BuildTrackStrategy buildTrackStrategy;
private boolean usingExistingTrack = false;
private final ReadOnlyWorld world;
private final FreerailsPrincipal principal;
public BuildTrackExplorer(ReadOnlyWorld w, FreerailsPrincipal principal) {
this(w, principal, null, new ImPoint(0, 0));
}
public BuildTrackExplorer(ReadOnlyWorld w, FreerailsPrincipal principal,
ImPoint start, ImPoint target) {
world = w;
this.principal = principal;
PositionOnTrack pos;
if (null == start) {
pos = new PositionOnTrack();
} else {
pos = PositionOnTrack
.createComingFrom(start.x, start.y, Step.NORTH);
}
currentPosition.setValuesFromInt(pos.toInt());
directionInt = 0;
this.target = target;
buildTrackStrategy = BuildTrackStrategy.getDefault(w);
}
/**
* <p>
* Tests whether we can build track in the direction specified by
* m_direction.
* </p>
*
* <p>
* If we enter a tile from a given direction, the tiles we can build track
* to depend on the following. (1) The terrain type of the surrounding tiles -
* track can only be built on certain terrain types. (2) The direction we
* entered the current tile from. (3) Any existing track on the current tile -
* limits possible track configurations. (4) The terrain type of the current
* tile - terrain type determines which track types and hence which track
* configurations can be built.
* </p>
*
*/
private boolean canBuildTrack() {
// Check that we are not doubling back on ourselves.
Step opposite2current = currentPosition.cameFrom().getOpposite();
int currentX = currentPosition.getX();
int currentY = currentPosition.getY();
int directionWeCameFrom = opposite2current.getID();
int directionWeCameFromPlus = (directionWeCameFrom + 1) % 8;
int directionWeCameFromMinus = (directionWeCameFrom + 7) % 8;
if (directionInt == directionWeCameFrom
|| directionInt == directionWeCameFromPlus
|| directionInt == directionWeCameFromMinus) {
return false;
}
// Check that we are not going off the map.
Step directionOfNextTile = Step.getInstance(directionInt);
int newX = currentX + directionOfNextTile.getDx();
int newY = currentY + directionOfNextTile.getDy();
if (!world.boundsContain(newX, newY)) {
return false;
}
TrackRule rule4nextTile;
TrackRule rule4lastTile;
// Determine the track rule for the next tile.
final FreerailsTile nextTile = (FreerailsTile) world.getTile(newX,
newY);
// Check there is not another players track at nextTile.
if (nextTile.hasTrack()) {
if (nextTile.getTrackPiece().getOwnerID() != world.getID(principal)) {
return false;
}
}
rule4nextTile = getAppropriateTrackRule(newX, newY);
if (null == rule4nextTile) {
return false; // We can't build track on the tile.
}
rule4lastTile = getAppropriateTrackRule(currentX, currentY);
if (null == rule4lastTile) {
return false; // We can't build track on the tile.
}
// Determine the track rule for the current tile.
FreerailsTile currentTile = (FreerailsTile) world.getTile(currentX,
currentY);
// Check for illegal track configurations.
final TrackConfiguration trackAlreadyPresent1 = currentTile
.getTrackPiece().getTrackConfiguration();
final TrackConfiguration trackAlreadyPresent2 = nextTile
.getTrackPiece().getTrackConfiguration();
TrackConfiguration fromConfig = trackAlreadyPresent1;
fromConfig = TrackConfiguration.add(fromConfig, opposite2current);
fromConfig = TrackConfiguration.add(fromConfig, TILE_CENTER);
Step goingTo = Step.getInstance(directionInt);
fromConfig = TrackConfiguration.add(fromConfig, goingTo);
if (!rule4lastTile.trackPieceIsLegal(fromConfig)) {
return false;
}
// Check for diagonal conflicts.
if (directionOfNextTile.isDiagonal()) {
int x2check = currentX;
int y2check = currentY + directionOfNextTile.deltaY;
// We did a bounds check above.
assert (world.boundsContain(x2check, y2check));
FreerailsTile tile2Check = (FreerailsTile) world.getTile(x2check,
y2check);
TrackConfiguration config2check = tile2Check
.getTrackPiece().getTrackConfiguration();
Step vector2check = Step.getInstance(directionOfNextTile.deltaX,
-directionOfNextTile.deltaY);
if (config2check.contains(vector2check)) {
// then we have a diagonal conflict.
return false;
}
}
// Check for illegal track configurations on the tile we are entering.
TrackConfiguration fromConfig2 = trackAlreadyPresent2;
fromConfig2 = TrackConfiguration.add(fromConfig2, TILE_CENTER);
Step goingBack = Step.getInstance(directionInt).getOpposite();
fromConfig2 = TrackConfiguration.add(fromConfig2, goingBack);
if (!rule4nextTile.trackPieceIsLegal(fromConfig2)) {
return false;
}
/*
* Set the using existing track. We do this because a path that uses
* existing track is cheaper to build.
*/
usingExistingTrack = trackAlreadyPresent1.contains(goingTo);
return true;
}
private TrackRule getAppropriateTrackRule(int x, int y) {
final FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
TrackRule rule;
if (!tile.hasTrack()) {
int terrainTypeID = tile.getTerrainTypeID();
int trackRuleID = buildTrackStrategy.getRule(terrainTypeID);
if (trackRuleID == -1) {
return null; // Can't build on this terrain!
}
rule = (TrackRule) world.get(SKEY.TRACK_RULES, trackRuleID);
} else {
rule = tile.getTrackPiece().getTrackRule();
}
return rule;
}
/**
* Calculates a cost figure incorporating the distance and the cost of any
* new track.
*/
public int getEdgeCost() {
if (beforeFirst) {
throw new IllegalStateException();
}
Step edgeDirection = Step.getInstance(directionInt - 1);
double length = edgeDirection.getLength();
final int DISTANCE_COST = 10000; // Same as the cost of standard
// track.
int cost = (int) Math.round(DISTANCE_COST * length);
if (!usingExistingTrack) {
int[] x = { currentPosition.getX(),
currentPosition.getX() + edgeDirection.deltaX };
int[] y = { currentPosition.getY(),
currentPosition.getY() + edgeDirection.deltaY };
TrackRule ruleA = getAppropriateTrackRule(x[0], y[0]);
TrackRule ruleB = getAppropriateTrackRule(x[1], y[1]);
/*
* If there is a station at either of the points, don't include its
* price in the cost calculation since it has already been paid.
* Otherwise, add the cost of building the track.
*/
long priceA = ruleA.getPrice().getAmount();
long priceB = ruleB.getPrice().getAmount();
cost += length * (priceA + priceB);
// Add fixed cost if tile b does not have the desired track type.
FreerailsTile a = (FreerailsTile) world.getTile(x[0], y[0]);
TrackRule currentRuleA = a.getTrackPiece().getTrackRule();
if (!currentRuleA.equals(ruleA)) {
assert (!currentRuleA.isStation()); // We shouldn't be upgrading
// a station.
cost += ruleA.getFixedCost().getAmount() * Step.TILE_DIAMETER;
}
}
return cost;
}
public int getH() {
int xDistance = (target.x - currentPosition.getX())
* Step.TILE_DIAMETER;
int yDistance = (target.y - currentPosition.getY())
* Step.TILE_DIAMETER;
int sumOfSquares = (xDistance * xDistance + yDistance * yDistance);
return (int) Math.sqrt(sumOfSquares);
}
public int getPosition() {
return currentPosition.toInt();
}
public int getVertexConnectedByEdge() {
if (beforeFirst) {
throw new IllegalStateException();
}
return currentBranch.toInt();
}
public boolean hasNextEdge() {
while (directionInt < 8) {
if (canBuildTrack()) {
return true;
}
directionInt++;
}
return false;
}
public void moveForward() {
if (beforeFirst) {
throw new IllegalStateException();
}
setPosition(this.getVertexConnectedByEdge());
}
public void nextEdge() {
if (!hasNextEdge()) {
throw new NoSuchElementException();
}
// The direction we are moving relative to the current position.
Step direction = Step.getInstance(directionInt);
currentBranch.setCameFrom(direction);
currentBranch.setX(currentPosition.getX() + direction.getDx());
currentBranch.setY(currentPosition.getY() + direction.getDy());
directionInt++;
beforeFirst = false;
}
public void setPosition(int vertex) {
currentPosition.setValuesFromInt(vertex);
directionInt = 0;
}
public void setBuildTrackStrategy(BuildTrackStrategy trackStrategy) {
if (null == trackStrategy)
throw new NullPointerException();
buildTrackStrategy = trackStrategy;
}
}

TrackMoveProducer

Full name: jfreerails.controller.TrackMoveProducer

Documentation

/**
* Provides methods that generate moves that build, upgrade, and remove track.
*
* @author Luke
*/

Source Code

/**
* Provides methods that generate moves that build, upgrade, and remove track.
*
* @author Luke
*/
final public class TrackMoveProducer {
private final ModelRoot mr;
private final MoveExecutor executor;
public enum BuildMode {
BUILD_TRACK, REMOVE_TRACK, UPGRADE_TRACK, IGNORE_TRACK, BUILD_STATION
}
private final Stack<Move> moveStack = new Stack<Move>();
private GameTime lastMoveTime = GameTime.BIG_BANG;
/**
* This generates the transactions - the charge - for the track being built.
*/
private final TrackMoveTransactionsGenerator transactionsGenerator;
public MoveStatus buildTrack(ImPoint from, Step[] path) {
MoveStatus returnValue = MoveStatus.MOVE_OK;
int x = from.x;
int y = from.y;
for (int i = 0; i < path.length; i++) {
returnValue = buildTrack(new ImPoint(x, y), path[i]);
x += path[i].deltaX;
y += path[i].deltaY;
if (!returnValue.ok) {
return returnValue;
}
}
return returnValue;
}
public MoveStatus buildTrack(ImPoint from, Step trackVector) {
ReadOnlyWorld w = executor.getWorld();
FreerailsPrincipal principal = executor.getPrincipal();
switch (getBuildMode()) {
case IGNORE_TRACK: {
return MoveStatus.MOVE_OK;
}
case REMOVE_TRACK: {
try {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateRemoveTrackMove(from, trackVector, w,
principal);
Move moveAndTransaction = transactionsGenerator
.addTransactions(move);
return sendMove(moveAndTransaction);
} catch (Exception e) {
// thrown when there is no track to remove.
// Fix for bug [ 948670 ] Removing non-existent track
return MoveStatus.moveFailed("No track to remove.");
}
}
case BUILD_TRACK:
case UPGRADE_TRACK:
/*
* Do nothing yet since we need to work out what type of track to
* build.
*/
break;
}
assert (getBuildMode() == BuildMode.BUILD_TRACK || getBuildMode() == BuildMode.UPGRADE_TRACK);
int[] ruleIDs = new int[2];
TrackRule[] rules = new TrackRule[2];
int[] xs = { from.x, from.x + trackVector.deltaX };
int[] ys = { from.y, from.y + trackVector.deltaY };
for (int i = 0; i < ruleIDs.length; i++) {
int x = xs[i];
int y = ys[i];
FreerailsTile tile = (FreerailsTile) w.getTile(x, y);
int tt = tile.getTerrainTypeID();
ruleIDs[i] = getBuildTrackStrategy().getRule(tt);
if (ruleIDs[i] == -1) {
TerrainType terrainType = (TerrainType) w.get(
SKEY.TERRAIN_TYPES, tt);
String message = "Non of the selected track types can be built on "
+ terrainType.getDisplayName();
return MoveStatus.moveFailed(message);
}
rules[i] = (TrackRule) w.get(SKEY.TRACK_RULES, ruleIDs[i]);
}
switch (getBuildMode()) {
case UPGRADE_TRACK: {
// upgrade the from tile if necessary.
FreerailsTile tileA = (FreerailsTile) w.getTile(from.x, from.y);
if (tileA.getTrackPiece().getTrackTypeID() != ruleIDs[0] && !isStationHere(from)) {
MoveStatus ms = upgradeTrack(from, ruleIDs[0]);
if (!ms.ok) {
return ms;
}
}
ImPoint point = new ImPoint(from.x + trackVector.getDx(), from.y
+ trackVector.getDy());
FreerailsTile tileB = (FreerailsTile) w.getTile(point.x, point.y);
if (tileB.getTrackPiece().getTrackTypeID() != ruleIDs[1] && !isStationHere(point)) {
MoveStatus ms = upgradeTrack(point, ruleIDs[1]);
if (!ms.ok) {
return ms;
}
}
return MoveStatus.MOVE_OK;
}
case BUILD_TRACK: {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(from, trackVector, rules[0],
rules[1], w, principal);
Move moveAndTransaction = transactionsGenerator
.addTransactions(move);
return sendMove(moveAndTransaction);
}
default:
throw new IllegalArgumentException(String.valueOf(getBuildMode()));
}
}
public MoveStatus upgradeTrack(ImPoint point) {
if (getBuildMode() == BuildMode.UPGRADE_TRACK) {
ReadOnlyWorld w = executor.getWorld();
FreerailsTile tile = (FreerailsTile) w.getTile(point.x, point.y);
int tt = tile.getTerrainTypeID();
return upgradeTrack(point, getBuildTrackStrategy().getRule(tt));
}
throw new IllegalStateException(
"Track builder not set to upgrade track!");
}
public void setTrackBuilderMode(BuildMode i) {
setBuildMode(i);
}
public TrackMoveProducer(MoveExecutor executor, ReadOnlyWorld world, ModelRoot mr) {
if(null == mr) throw new NullPointerException();
this.executor = executor;
this.mr = mr;
FreerailsPrincipal principal = executor.getPrincipal();
transactionsGenerator = new TrackMoveTransactionsGenerator(world,
principal);
setBuildTrackStrategy(BuildTrackStrategy.getDefault(world));
}
public TrackMoveProducer(ModelRoot mr) {
this.executor = mr;
if(null == mr) throw new NullPointerException();
this.mr = mr;
ReadOnlyWorld world = executor.getWorld();
FreerailsPrincipal principal = executor.getPrincipal();
transactionsGenerator = new TrackMoveTransactionsGenerator(world,
principal);
setBuildTrackStrategy(BuildTrackStrategy.getDefault(world));
}
private MoveStatus upgradeTrack(ImPoint point, int trackRuleID) {
ReadOnlyWorld w = executor.getWorld();
TrackPiece before = ((FreerailsTile) w.getTile(point.x, point.y)).getTrackPiece();
/* Check whether there is track here. */
if (before.getTrackTypeID() == NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
return MoveStatus.moveFailed("No track to upgrade.");
}
FreerailsPrincipal principal = executor.getPrincipal();
int owner = ChangeTrackPieceCompositeMove.getOwner(principal, w);
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, trackRuleID);
TrackPiece after = new TrackPieceImpl(before.getTrackConfiguration(),
trackRule, owner, trackRuleID);
/* We don't want to 'upgrade' a station to track. See bug 874416. */
if (before.getTrackRule().isStation()) {
return MoveStatus
.moveFailed("No need to upgrade track at station.");
}
Move move = UpgradeTrackMove.generateMove(before, after, point);
Move move2 = transactionsGenerator.addTransactions(move);
return sendMove(move2);
}
public MoveStatus undoLastTrackMove() {
clearStackIfStale();
if (moveStack.size() > 0) {
Move m = moveStack.pop();
UndoMove undoMove = new UndoMove(m);
MoveStatus ms = executor.doMove(undoMove);
if (!ms.ok) {
return MoveStatus.moveFailed("Can not undo building track!");
}
return ms;
}
return MoveStatus.moveFailed("No track to undo building!");
}
/**
* Moves are only un-doable if no game time has passed since they they were
* executed. This method clears the move stack if the moves were added to
* the stack at a time other than the current time.
*/
private void clearStackIfStale() {
ReadOnlyWorld w = executor.getWorld();
GameTime currentTime = w.currentTime();
if (!currentTime.equals(lastMoveTime)) {
moveStack.clear();
lastMoveTime = currentTime;
}
}
public BuildMode getTrackBuilderMode() {
return getBuildMode();
}
private MoveStatus sendMove(Move m) {
MoveStatus ms = executor.doMove(m);
if (ms.isOk()) {
clearStackIfStale();
moveStack.add(m);
}
return ms;
}
// public BuildTrackStrategy getBuildTrackStrategy() {
// return buildTrackStrategy;
// }
//
// public void setBuildTrackStrategy(BuildTrackStrategy buildTrackStrategy) {
// this.buildTrackStrategy = buildTrackStrategy;
// }
private boolean isStationHere(ImPoint p) {
ReadOnlyWorld w = executor.getWorld();
FreerailsTile tile = (FreerailsTile) w.getTile(p.x, p.y);
return tile.getTrackPiece().getTrackRule().isStation();
}
public void setBuildTrackStrategy(BuildTrackStrategy buildTrackStrategy) {
mr.setProperty(Property.BUILD_TRACK_STRATEGY, buildTrackStrategy);
}
public BuildTrackStrategy getBuildTrackStrategy() {
return (BuildTrackStrategy) mr.getProperty(Property.BUILD_TRACK_STRATEGY);
}
public void setBuildMode(BuildMode buildMode) {
mr.setProperty(Property.TRACK_BUILDER_MODE, buildMode);
}
public BuildMode getBuildMode() {
return (BuildMode) mr.getProperty(Property.TRACK_BUILDER_MODE);
}
}

TimeTickPreMove

Full name: jfreerails.controller.TimeTickPreMove

Documentation

/**
* Generates a TimeTickMove.
*
* @author Luke
*
*/

Source Code

/**
* Generates a TimeTickMove.
*
* @author Luke
*
*/
@jfreerails.util.InstanceControlled
public class TimeTickPreMove implements PreMove {
private static final long serialVersionUID = 3690479125647208760L;
public static final TimeTickPreMove INSTANCE = new TimeTickPreMove();
private TimeTickPreMove() {
}
public Move generateMove(ReadOnlyWorld w) {
return TimeTickMove.getMove(w);
}
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
}

IncrementalPathFinder

Full name: jfreerails.controller.IncrementalPathFinder

Documentation

/**
* Defines part of the contract for a pathfinder whose search can be completed
* in several steps.
*
* @author Luke
*
*/

Source Code

/**
* Defines part of the contract for a pathfinder whose search can be completed
* in several steps.
*
* @author Luke
*
*/
public interface IncrementalPathFinder {
// TODO replace with enum.
public static final int PATH_NOT_FOUND = Integer.MIN_VALUE;
public final int PATH_FOUND = Integer.MIN_VALUE + 1;
public static final int SEARCH_PAUSED = Integer.MIN_VALUE + 2;
public static final int SEARCH_NOT_STARTED = Integer.MIN_VALUE + 3;
public abstract int getStatus();
public abstract void search(long maxDuration) throws PathNotFoundException;
public abstract void abandonSearch();
}

FinancialDataGatherer

Full name: jfreerails.controller.FinancialDataGatherer

Documentation

/**
* Gathers the financial data for a company.
*
* @author Luke
* @author smackay
*/

Source Code

/**
* Gathers the financial data for a company.
*
* @author Luke
* @author smackay
*/
public class FinancialDataGatherer extends TransactionAggregator {
private int totalShares = 100000;
private final int playerID;
private int bonds;
private int[] stockInRRs;
private int[] stockInThisRRs;
@Override
protected void incrementRunningTotal(int transactionID) {
Transaction t = super.w.getTransaction(super.principal, transactionID);
if (t instanceof AddItemTransaction) {
AddItemTransaction ait = (AddItemTransaction) t;
if (t instanceof StockTransaction
&& ait.getCategory() == Transaction.Category.ISSUE_STOCK
&& ait.getType() == -1) {
// If it is a change in the total number of shares issued.
StockTransaction ist = (StockTransaction) t;
totalShares += ist.getQuantity();
} else if (t instanceof StockTransaction
&& ait.getCategory() == Transaction.Category.TRANSFER_STOCK
) {
//
stockInRRs[ait.getType()] += ait.getQuantity();
} else if (t instanceof BondTransaction) {
bonds += ait.getQuantity();
}
} else {
super.incrementRunningTotal(transactionID);
}
}
@Override
protected void setTotalsArrayLength(int length) {
// TODO Auto-generated method stub
super.setTotalsArrayLength(length);
}
@Override
protected void storeRunningTotal(int timeIndex) {
// TODO Auto-generated method stub
super.storeRunningTotal(timeIndex);
}
public FinancialDataGatherer(ReadOnlyWorld w, FreerailsPrincipal principal) {
super(w, principal);
stockInRRs = new int [w.getNumberOfPlayers()];
calculateValues();
this.playerID = w.getID(principal);
}
public void changeTreasuryStock(int deltaStock) {
}
public void changeStake(int stakeHolder, int deltaStock) {
}
public boolean canIssueBond() {
return nextBondInterestRate() <= 7;
}
public boolean canBuyStock() {
return totalShares > 0;
}
public int nextBondInterestRate() {
EconomicClimate ec = (EconomicClimate) w.get(ITEM.ECONOMIC_CLIMATE);
return bonds + ec.getBaseInterestRate();
}
public int[] bondInterestRates() {
return null;
}
/** Returns the number of stock in the Treasury */
public int treasuryStock() {
return stockInRRs[playerID];
}
/** Returns The number of open Shares */
public int totalShares() {
return totalShares;
}
public int sharesHeldByPublic(){
int[]stock = getStockInThisRRs();
int returnValue = this.totalShares;
for (int i = 0; i < stock.length; i++) {
returnValue -= stock[i];
}
return returnValue;
}
public boolean thisRRHasStakeIn(int otherReId){
return stockInRRs[otherReId] > 0;
}
public Money netWorth() {
NetWorthCalculator nwc = new NetWorthCalculator(w, principal);
GameTime[] times = {GameTime.BIG_BANG, GameTime.END_OF_THE_WORLD};
nwc.setTimes(times);
return nwc.calculateValue();
}
@Override
protected boolean condition(int transactionID) {
// We'll do the work when incrementRunningTotal gets called.
return true;
}
public int[] getStockInThisRRs() {
if(null == stockInThisRRs){
stockInThisRRs = new int[w.getNumberOfPlayers()];
for(int i = 0; i < w.getNumberOfPlayers(); i++){
Player p = w.getPlayer(i);
FinancialDataGatherer temp = new FinancialDataGatherer(w, p.getPrincipal());
stockInThisRRs[i] = temp.stockInRRs[this.playerID];
}
}
return stockInThisRRs;
}
public int[] getStockInRRs() {
return stockInRRs;
}
public int getBonds() {
return bonds;
}
}

SimpleAStarPathFinder

Full name: jfreerails.controller.SimpleAStarPathFinder

Documentation

/**
* A simple A* pathfinder implementation. It uses int's to avoid the cost of
* object creation and garbage collection. 26-Nov-2002
*
* @author Luke Lindsay
*
*/

Source Code

/**
* A simple A* pathfinder implementation. It uses int's to avoid the cost of
* object creation and garbage collection. 26-Nov-2002
*
* @author Luke Lindsay
*
*/
public class SimpleAStarPathFinder implements Serializable,
IncrementalPathFinder {
private static final long serialVersionUID = 3257565105200576310L;
private static final Logger logger = Logger
.getLogger(SimpleAStarPathFinder.class.getName());
private OpenList openList = new OpenList();
private final HashSet<Integer> startingPositions = new HashSet<Integer>();
private final HashMap<Integer, Integer> closedList = new HashMap<Integer, Integer>();
private final HashMap<Integer, Integer> shortestPath = new HashMap<Integer, Integer>();
private int status = SEARCH_NOT_STARTED;
/** Note, IntArray is not Serializable. */
private transient IntArray path = null;
private int bestPath;
private int bestPathF;
private GraphExplorer explorer;
private long searchStartTime = 0;
public int getStatus() {
return status;
}
public IntArray retrievePath() {
return path;
}
public int findstep(int currentPosition, int[] targets,
GraphExplorer tempExplorer) {
try {
return findpath(new int[] { currentPosition }, targets,
tempExplorer).get(0);
} catch (PathNotFoundException e) {
return PATH_NOT_FOUND;
}
}
public IntArray findpath(int[] currentPosition, int[] targets,
GraphExplorer e) throws PathNotFoundException {
logger.fine(currentPosition.length + " starting points; "
+ targets.length + " targets.");
setupSearch(currentPosition, targets, e);
search(-1);
return path;
}
public void search(long maxDuration) throws PathNotFoundException {
long iterationStartTime = 0;
boolean check4timeout = false;
if (maxDuration > 0) {
check4timeout = true;
iterationStartTime = System.currentTimeMillis();
if (searchStartTime == 0) {
searchStartTime = iterationStartTime;
}
}
int loopCounter = 0;
// while the open list is not empty
while (openList.size() > 0) {
// find the node with the least f on the open list, call it "q"
// pop q off the open list
int f = openList.smallestF();
int q = openList.popNodeWithSmallestF();
// generate q's successors.
explorer.setPosition(q);
// for each successor
while (explorer.hasNextEdge()) {
explorer.nextEdge();
int successor = explorer.getVertexConnectedByEdge();
int successorF = f + explorer.getEdgeCost();
// for now, let successor.h=0
// successor.g = q.g + distance between successor and q
// successor.h = distance from goal to successor
// successor.f = successor.g + successor.h
if (startingPositions.contains(successor)) {
// if successor is the goal, we have found a path, but not
// necessarily the shortest.
if (bestPathF > successorF) {
bestPath = q;
bestPathF = successorF;
}
}
if (openList.contains(successor)
&& openList.getF(successor) < successorF) {
// if a node with the same position as successor is in the
// OPEN list \
// which has a lower f than successor, skip this successor
continue;
} else if (closedList.containsKey(successor)
&& closedList.get(successor) < successorF) {
// if a node with the same position as successor is in the
// CLOSED list \
// which has a lower f than successor, skip this successor
continue;
} else {
// otherwise, add the node to the open list
openList.add(successor, successorF);
shortestPath.put(successor, q);
}
}
if (PATH_NOT_FOUND != bestPath) {
int SmallestFOnOpenList = openList.smallestF();
if (bestPathF <= SmallestFOnOpenList) {
// if the F value for the best path we have found so far is
// less than that of the node with the smallest F value on
// the open list, then the best path so far is the shortest
// path.
logger.fine("Path successfully found after " + loopCounter
+ " iterations.");
path.add(bestPath);
int step = bestPath;
while (shortestPath.containsKey(step)) {
step = shortestPath.get(step);
path.add(step);
}
logger.fine("Path found!");
status = PATH_FOUND;
return;
}
}
// push q on the closed list
// PositionOnTrack p = new PositionOnTrack(q);
closedList.put(q, f);
loopCounter++;
// Check whether we have been searching too long.
if (check4timeout && loopCounter % 50 == 0) {
long currentTime = System.currentTimeMillis();
long deltatime = currentTime - iterationStartTime;
if (deltatime > maxDuration) {
status = SEARCH_PAUSED;
long totalSearchTime = currentTime - searchStartTime;
throw new PathNotFoundException("No path found yet. "
+ totalSearchTime + "ms.");
}
}
}
status = PATH_NOT_FOUND;
logger.fine("No path found and open list empty after " + loopCounter
+ " iterations.");
throw new PathNotFoundException("Path not found.");
}
public void setupSearch(int[] currentPosition, int[] targets,
GraphExplorer e) throws PathNotFoundException {
abandonSearch();
explorer = e;
// put the starting nodes on the open list (you can leave its f at zero)
for (int i = 0; i < targets.length; i++) {
openList.add(targets[i], 0);
for (int j = 0; j < currentPosition.length; j++) {
if (targets[i] == currentPosition[j]) {
status = PATH_NOT_FOUND;
throw new PathNotFoundException("Already at target!");
}
}
}
for (int j = 0; j < currentPosition.length; j++) {
startingPositions.add(currentPosition[j]);
}
}
public void abandonSearch() {
path = new IntArray();
searchStartTime = 0;
bestPath = PATH_NOT_FOUND;
bestPathF = Integer.MAX_VALUE;
// initialize the open list
openList.clear();
// initialize the closed list
closedList.clear();
shortestPath.clear();
startingPositions.clear();
status = SEARCH_NOT_STARTED;
}
}

MyDisplayMode

Full name: jfreerails.controller.MyDisplayMode

Documentation

/**
* Stores a DisplayMode and provides a customised implementation of toString
* that can be used in menus.
*
* @author Luke Lindsay
*/

Source Code

/**
* Stores a DisplayMode and provides a customised implementation of toString
* that can be used in menus.
*
* @author Luke Lindsay
*/
public class MyDisplayMode {
public final DisplayMode displayMode;
public MyDisplayMode(DisplayMode displayMode) {
this.displayMode = displayMode;
}
@Override
public String toString() {
return displayMode.getWidth() + "x" + displayMode.getHeight() + " "
+ displayMode.getBitDepth() + " bit "
+ displayMode.getRefreshRate() + "Hz";
}
@Override
public int hashCode() {
return displayMode.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof MyDisplayMode) {
MyDisplayMode test = (MyDisplayMode) o;
return test.displayMode.equals(this.displayMode);
}
return false;
}
}

CargoElementObject

Full name: jfreerails.controller.CargoElementObject

Documentation

/**
* Small data object to store the rate of supply of a cargo.
*
* @author Scott Bennett Date: 14 May 2003
*/

Source Code

/**
* Small data object to store the rate of supply of a cargo.
*
* @author Scott Bennett Date: 14 May 2003
*/
public class CargoElementObject {
private int rate;
private final int type;
public CargoElementObject(int rate, int type) {
this.rate = rate;
this.type = type;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
public int getType() {
return type;
}
}

UnexpectedExceptionForm

Full name: jfreerails.controller.UnexpectedExceptionForm

Documentation

/**
*
* @author Luke
*/

Source Code

/**
*
* @author Luke
*/
public class UnexpectedExceptionForm extends javax.swing.JFrame {
private static final long serialVersionUID = -4348641764811196495L;
/** Creates new form UnexpectedExceptionForm */
public UnexpectedExceptionForm() {
initComponents();
}
public void setText(String s){
copyableTextJPanel1.setText(s);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
copyableTextJPanel1 = new jfreerails.controller.CopyableTextJPanel();
closebutton = new javax.swing.JButton();
getContentPane().setLayout(new java.awt.GridBagLayout());
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Unexpected Exception");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(copyableTextJPanel1, gridBagConstraints);
closebutton.setText("Close");
closebutton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closebuttonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
getContentPane().add(closebutton, gridBagConstraints);
pack();
}
// </editor-fold>//GEN-END:initComponents
private void closebuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closebuttonActionPerformed
System.exit(1);
}//GEN-LAST:event_closebuttonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
UnexpectedExceptionForm unexpectedExceptionForm = new UnexpectedExceptionForm();
Exception e = new Exception("Oh No..");
String str = ReportBugTextGenerator.genText(e);
unexpectedExceptionForm.setText(str);
unexpectedExceptionForm.setVisible(true);
e.printStackTrace();
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JButton closebutton;
jfreerails.controller.CopyableTextJPanel copyableTextJPanel1;
// End of variables declaration//GEN-END:variables
}

PreMoveStatus

Full name: jfreerails.controller.PreMoveStatus

Documentation

/**
* Records the success or failure of an attempt to execute a move.
*
* @author lindsal
*/

Source Code

/**
* Records the success or failure of an attempt to execute a move.
*
* @author lindsal
*/
final public class PreMoveStatus implements FreerailsSerializable {
private static final long serialVersionUID = 3978145456646009140L;
public static final PreMoveStatus PRE_MOVE_OK = new PreMoveStatus(
MoveStatus.MOVE_OK);
public final MoveStatus ms;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof PreMoveStatus))
return false;
final PreMoveStatus preMoveStatus = (PreMoveStatus) o;
if (!ms.equals(preMoveStatus.ms))
return false;
return true;
}
@Override
public int hashCode() {
return ms.hashCode();
}
/**
* Avoid creating a duplicate when deserializing.
*/
private Object readResolve() {
if (ms.ok) {
return PRE_MOVE_OK;
}
return this;
}
private PreMoveStatus(MoveStatus ms) {
this.ms = ms;
}
public static PreMoveStatus failed(String reason) {
return new PreMoveStatus(MoveStatus.moveFailed(reason));
}
public static PreMoveStatus fromMoveStatus(MoveStatus ms) {
if (ms.ok) {
return PRE_MOVE_OK;
}
return new PreMoveStatus(ms);
}
}

PreMove

Full name: jfreerails.controller.PreMove

Documentation

/**
* Defines a method that generates a move based on the state of the world
* object. The state of a move is often a function of the state of the world
* object and some other input.
*
* @author Luke
*
*/

Source Code

/**
* Defines a method that generates a move based on the state of the world
* object. The state of a move is often a function of the state of the world
* object and some other input.
*
* @author Luke
*
*/
public interface PreMove extends FreerailsSerializable {
Move generateMove(ReadOnlyWorld w);
}

Methods

DropOffAndPickupCargoMoveGenerator

Full name: jfreerails.controller.DropOffAndPickupCargoMoveGenerator

Documentation

/**
* This class generates moves that transfer cargo between train and the stations
* it stops at - it also handles cargo conversions that occur when cargo is
* dropped off.
*
* @author Scott Bennett
* @author Luke Lindsay Date Created: 4 June 2003
*/

Source Code

/**
* This class generates moves that transfer cargo between train and the stations
* it stops at - it also handles cargo conversions that occur when cargo is
* dropped off.
*
* @author Scott Bennett
* @author Luke Lindsay Date Created: 4 June 2003
*/
public class DropOffAndPickupCargoMoveGenerator {
private final ReadOnlyWorld w;
private final TrainAccessor train;
private final int trainId;
private int trainBundleId;
private final int stationId;
private int stationBundleId;
private MutableCargoBundle stationAfter;
private MutableCargoBundle stationBefore;
private MutableCargoBundle trainAfter;
private MutableCargoBundle trainBefore;
private ArrayList<Move> moves;
private final FreerailsPrincipal principal;
private boolean waitingForFullLoad;
private boolean autoConsist;
private ImInts consist = new ImInts();
/**
* Stores the type and quantity of cargo in a wagon.
*
* @author Luke
*/
private static class WagonLoad implements Comparable<WagonLoad> {
final int quantity;
final int cargoType;
public int compareTo(WagonLoad test) {
return quantity - test.quantity;
}
WagonLoad(int q, int t) {
quantity = q;
cargoType = t;
}
}
/**
* Constructor.
*
* @param trainNo
* ID of the train
* @param stationNo
* ID of the station
* @param world
* The world object
*/
public DropOffAndPickupCargoMoveGenerator(int trainNo, int stationNo, ReadOnlyWorld world,
FreerailsPrincipal p, boolean waiting, boolean autoConsist) {
principal = p;
trainId = trainNo;
stationId = stationNo;
w = world;
this.autoConsist = autoConsist;
this.waitingForFullLoad = waiting;
train = new TrainAccessor(w, principal, trainNo);
consist = train.getTrain().getConsist();
getBundles();
processTrainBundle(); // ie. unload train / dropoff cargo
if (autoConsist) {
ArrayList<WagonLoad> wagonsAvailable = new ArrayList<WagonLoad>();
assert (train.equals(world.get(principal, KEY.TRAINS, this.trainId)));
Schedule schedule = train.getSchedule();
TrainOrdersModel order = schedule.getOrder(schedule.getOrderToGoto());
int nextStationId = order.stationId;
StationModel stationModel = (StationModel) w
.get(principal, KEY.STATIONS, nextStationId);
Demand4Cargo demand = stationModel.getDemand();
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
// If this cargo is demanded at the next scheduled station.
if (demand.isCargoDemanded(i)) {
int amount = stationAfter.getAmount(i);
while (amount > 0) {
int amount2remove = Math.min(amount, WagonType.UNITS_OF_CARGO_PER_WAGON);
amount -= amount2remove;
// Don't bother with less than half a wagon load.
if (amount2remove * 2 > WagonType.UNITS_OF_CARGO_PER_WAGON) {
wagonsAvailable.add(new WagonLoad(amount2remove, i));
}
}
}
}
Collections.sort(wagonsAvailable);
int numWagons2add = Math.min(wagonsAvailable.size(), 3);
int[] temp = new int[numWagons2add];
for (int i = 0; i < numWagons2add; i++) {
WagonLoad wagonload = wagonsAvailable.get(i);
temp[i] = wagonload.cargoType;
}
consist = new ImInts(temp);
}
processStationBundle(); // ie. load train / pickup cargo
}
public Move generateMove() {
// The methods that calculate the before and after bundles could be
// called from here.
ChangeCargoBundleMove changeAtStation = new ChangeCargoBundleMove(stationBefore
.toImmutableCargoBundle(), stationAfter.toImmutableCargoBundle(), stationBundleId,
principal);
ChangeCargoBundleMove changeOnTrain = new ChangeCargoBundleMove(trainBefore
.toImmutableCargoBundle(), trainAfter.toImmutableCargoBundle(), trainBundleId,
principal);
moves.add(TransferCargoAtStationMove.CHANGE_AT_STATION_INDEX, changeAtStation);
moves.add(TransferCargoAtStationMove.CHANGE_ON_TRAIN_INDEX, changeOnTrain);
if (autoConsist) {
int engine = train.getTrain().getEngineType();
Move m = ChangeTrainMove.generateMove(this.trainId, train.getTrain(), engine, consist, principal);
moves.add(m);
} else if (waitingForFullLoad) {
// Only generate a move if there is some cargo to add..
if (changeOnTrain.beforeEqualsAfter())
return null;
}
TransferCargoAtStationMove move = new TransferCargoAtStationMove(moves, waitingForFullLoad);
assert move.getChangeAtStation() == changeAtStation;
assert move.getChangeOnTrain() == changeOnTrain;
return move;
}
private void getBundles() {
TrainModel trainModel = ((TrainModel) w.get(principal, KEY.TRAINS, trainId));
trainBundleId = trainModel.getCargoBundleID();
trainBefore = getCopyOfBundle(trainBundleId);
trainAfter = getCopyOfBundle(trainBundleId);
StationModel stationModel = ((StationModel) w.get(principal, KEY.STATIONS, stationId));
stationBundleId = stationModel.getCargoBundleID();
stationAfter = getCopyOfBundle(stationBundleId);
stationBefore = getCopyOfBundle(stationBundleId);
}
private MutableCargoBundle getCopyOfBundle(int id) {
FreerailsSerializable fs = w.get(principal, KEY.CARGO_BUNDLES, id);
ImmutableCargoBundle ibundle = (ImmutableCargoBundle) fs;
return new MutableCargoBundle(ibundle);
}
private void processTrainBundle() {
Iterator<CargoBatch> batches = trainAfter.toImmutableCargoBundle().cargoBatchIterator();
StationModel station = (StationModel) w.get(principal, KEY.STATIONS, stationId);
MutableCargoBundle cargoDroppedOff = new MutableCargoBundle();
// Unload the cargo that the station demands
while (batches.hasNext()) {
CargoBatch cb = batches.next();
// if the cargo is demanded and its not from this station
// originally...
Demand4Cargo demand = station.getDemand();
int cargoType = cb.getCargoType();
if ((demand.isCargoDemanded(cargoType)) && (stationId != cb.getStationOfOrigin())) {
int amount = trainAfter.getAmount(cb);
cargoDroppedOff.addCargo(cb, amount);
// Now perform any conversions..
ConvertedAtStation converted = station.getConverted();
if (converted.isCargoConverted(cargoType)) {
int newCargoType = converted.getConversion(cargoType);
CargoBatch newCargoBatch = new CargoBatch(newCargoType, station.x, station.y,
0, stationId);
stationAfter.addCargo(newCargoBatch, amount);
}
trainAfter.setAmount(cb, 0);
}
}
moves = ProcessCargoAtStationMoveGenerator.processCargo(w, cargoDroppedOff, this.stationId,
principal, trainId);
// Unload the cargo that there isn't space for on the train regardless
// of whether the station
// demands it.
ImInts spaceAvailable = train.spaceAvailable();
for (int cargoType = 0; cargoType < spaceAvailable.size(); cargoType++) {
int quantity = spaceAvailable.get(cargoType);
if (quantity < 0) {
int amount2transfer = -quantity;
transferCargo(cargoType, amount2transfer, trainAfter, stationAfter);
}
}
}
/** Transfer cargo from the station to the train subject to the space available on the train.
*/
private void processStationBundle() {
ImInts spaceAvailable = TrainAccessor.spaceAvailable2(w, trainAfter.toImmutableCargoBundle(), consist);
for (int cargoType = 0; cargoType < spaceAvailable.size(); cargoType++) {
int quantity = spaceAvailable.get(cargoType);
int amount2transfer = Math.min(quantity, stationAfter
.getAmount(cargoType));
transferCargo(cargoType, amount2transfer, stationAfter, trainAfter);
}
}
public boolean isCargo2Transfer() {
ImInts spaceAvailable = train.spaceAvailable();
int total = 0;
for (int cargoType = 0; cargoType < w.size(SKEY.CARGO_TYPES); cargoType++) {
int quantity = spaceAvailable.get(cargoType);
int amount2transfer = Math.min(quantity, stationAfter
.getAmount(cargoType));
total += amount2transfer;
}
return total > 0;
}
/**
* Move the specified quantity of the specified cargotype from one bundle to
* another.
*/
private static void transferCargo(int cargoTypeToTransfer, int amountToTransfer,
MutableCargoBundle from, MutableCargoBundle to) {
if (0 == amountToTransfer) {
return;
}
Iterator<CargoBatch> batches = from.toImmutableCargoBundle().cargoBatchIterator();
int amountTransferredSoFar = 0;
while (batches.hasNext() && amountTransferredSoFar < amountToTransfer) {
CargoBatch cb = batches.next();
if (cb.getCargoType() == cargoTypeToTransfer) {
int amount = from.getAmount(cb);
int amountOfThisBatchToTransfer;
if (amount < amountToTransfer - amountTransferredSoFar) {
amountOfThisBatchToTransfer = amount;
from.setAmount(cb, 0);
} else {
amountOfThisBatchToTransfer = amountToTransfer - amountTransferredSoFar;
from.addCargo(cb, -amountOfThisBatchToTransfer);
}
to.addCargo(cb, amountOfThisBatchToTransfer);
amountTransferredSoFar += amountOfThisBatchToTransfer;
}
}
}
}

MoveExecutor

Full name: jfreerails.controller.MoveExecutor

Documentation

/**
* Lets the caller try and execute Moves.
*
* @author Luke
*
*/

Source Code

/**
* Lets the caller try and execute Moves.
*
* @author Luke
*
*/
public interface MoveExecutor {
MoveStatus doMove(Move m);
MoveStatus doPreMove(PreMove pm);
MoveStatus tryDoMove(Move m);
ReadOnlyWorld getWorld();
FreerailsPrincipal getPrincipal();
}

MessageStatus

Full name: jfreerails.controller.MessageStatus

Documentation

/**
* An instance of this class is returned to the client (the server) when a
* Message2Server (Message2Client) is executed by the server (the client).
*
* @see Message2Client
* @see Message2Server
* @author Luke
*
*/

Source Code

/**
* An instance of this class is returned to the client (the server) when a
* Message2Server (Message2Client) is executed by the server (the client).
*
* @see Message2Client
* @see Message2Server
* @author Luke
*
*/
public class MessageStatus implements FreerailsSerializable {
private static final long serialVersionUID = 3257285842216103987L;
private final int id;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof MessageStatus))
return false;
final MessageStatus messageStatus = (MessageStatus) o;
if (id != messageStatus.id)
return false;
if (successful != messageStatus.successful)
return false;
if (reason != null ? !reason.equals(messageStatus.reason)
: messageStatus.reason != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + (reason != null ? reason.hashCode() : 0);
result = 29 * result + (successful ? 1 : 0);
return result;
}
private final String reason;
private final boolean successful;
public MessageStatus(int id, boolean successful, String reason) {
this.id = id;
this.reason = reason;
this.successful = successful;
}
public MessageStatus(int id, boolean successful) {
this.id = id;
this.reason = null;
this.successful = successful;
}
/** Returns the id of the command whose status this object stores. */
public int getId() {
return id;
}
/** Returns the reason the command failed, may be null. */
public String getReason() {
return reason;
}
/** True if the command was successfully executed. */
public boolean isSuccessful() {
return successful;
}
}

ServerControlInterface

Full name: jfreerails.controller.ServerControlInterface

Documentation

/**
* Defines the methods that a client can call on the server using a
* Message2Server.
*
* @see Message2Server
* @author Luke
*
*/

Source Code

/**
* Defines the methods that a client can call on the server using a
* Message2Server.
*
* @see Message2Server
* @author Luke
*
*/
public interface ServerControlInterface {
public static final String FREERAILS_SAV = "freerails.sav";
public static final String VERSION = "CVS";
void loadgame(String saveGameName) throws IOException;
void savegame(String saveGameName);
void stopGame();
void refreshSavedGames();
void newGame(String mapName);
}

SimpleMoveExecutor

Full name: jfreerails.controller.SimpleMoveExecutor

Documentation

/**
* A MoveExecutor that executes moves on the world object passed to its
* constructor.
*
* @author Luke
*
*/

Source Code

/**
* A MoveExecutor that executes moves on the world object passed to its
* constructor.
*
* @author Luke
*
*/
public class SimpleMoveExecutor implements MoveExecutor {
private final World w;
private final FreerailsPrincipal p;
public SimpleMoveExecutor(World world, int playerID) {
w = world;
Player player = w.getPlayer(playerID);
p = player.getPrincipal();
}
public MoveStatus doMove(Move m) {
return m.doMove(w, p);
}
public MoveStatus doPreMove(PreMove pm) {
Move m = pm.generateMove(w);
return m.doMove(w, p);
}
public MoveStatus tryDoMove(Move m) {
return m.tryDoMove(w, p);
}
public ReadOnlyWorld getWorld() {
return w;
}
public FreerailsPrincipal getPrincipal() {
return p;
}
}

TrainAccessor

Full name: jfreerails.controller.TrainAccessor

Documentation

/**
* Provides convenience methods to access the properties of a train from the
* world object.
*
* @author Luke
*
*/

Source Code

/**
* Provides convenience methods to access the properties of a train from the
* world object.
*
* @author Luke
*
*/
public class TrainAccessor {
private final ReadOnlyWorld w;
private final FreerailsPrincipal p;
private final int id;
public TrainAccessor(final ReadOnlyWorld w, final FreerailsPrincipal p,
final int id) {
this.w = w;
this.p = p;
this.id = id;
}
public int getId() {
return id;
}
public SpeedTimeAndStatus.TrainActivity getStatus(double time){
TrainMotion tm = findCurrentMotion(time);
return tm.getActivity();
}
/**
* Checks the track under the train's final position still exists (i.e.
* has not been bulldozed).
*/
public boolean trackExists() {
ActivityIterator ai = w.getActivities(p, id);
ai.gotoLastActivity();
TrainMotion tm = (TrainMotion) ai.getActivity();
PositionOnTrack pot = tm.getFinalPosition();
int x = pot.getX();
int y = pot.getY();
FreerailsTile tile = (FreerailsTile) w.getTile(x, y);
TrackPiece trackPiece = tile.getTrackPiece();
TrackConfiguration present = trackPiece.getTrackConfiguration();
TrackConfiguration needed = TrackConfiguration.getFlatInstance(pot.cameFrom());
return present.contains(needed);
}
/**
* @return the id of the station the train is currently at, or -1 if no
* current station.
*
*/
public int getStationId(double time){
TrainMotion tm = findCurrentMotion(time);
PositionOnTrack pot = tm.getFinalPosition();
int x = pot.getX();
int y = pot.getY();
//loop thru the station list to check if train is at the same Point
// as
// a station
for (int i = 0; i < w.size(p, KEY.STATIONS); i++) {
StationModel tempPoint = (StationModel) w.get(p, KEY.STATIONS, i);
if (null != tempPoint && (x == tempPoint.x) && (y == tempPoint.y)) {
return i; // train is at the station at location tempPoint
}
}
return -1;
}
public TrainPositionOnMap findPosition(double time) {
ActivityIterator ai = w.getActivities(p, id);
ai.gotoLastActivity();
while (ai.getStartTime() > time && ai.hasPrevious()) {
ai.previousActivity();
}
double dt = time - ai.getStartTime();
dt = Math.min(dt, ai.getDuration());
TrainMotion tm = (TrainMotion) ai.getActivity();
return tm.getState(dt);
}
public TrainMotion findCurrentMotion(double time) {
ActivityIterator ai = w.getActivities(p, id);
ai.gotoLastActivity();
while (ai.getStartTime() > time && ai.hasPrevious()) {
ai.previousActivity();
}
return (TrainMotion) ai.getActivity();
}
public TrainModel getTrain() {
return (TrainModel) w.get(p, KEY.TRAINS, id);
}
public ImmutableSchedule getSchedule() {
TrainModel train = getTrain();
return (ImmutableSchedule) w.get(p, KEY.TRAIN_SCHEDULES, train
.getScheduleID());
}
public ImmutableCargoBundle getCargoBundle() {
TrainModel train = getTrain();
return (ImmutableCargoBundle) w.get(p, KEY.CARGO_BUNDLES, train
.getCargoBundleID());
}
/**
* Returns true iff all the following hold.
* <ol>
* <li>The train is waiting for a full load at some station X.</li>
* <li>The current train order tells the train to goto station X.</li>
* <li>The current train order tells the train to wait for a full load.</li>
* <li>The current train order specifies a consist that matches the train's current consist.</li>
* </ol>
*
*/
public boolean keepWaiting(){
double time = w.currentTime().getTicks();
int stationId = getStationId(time);
if (stationId == -1)
return false;
SpeedTimeAndStatus.TrainActivity act = getStatus(time);
if (act != TrainActivity.WAITING_FOR_FULL_LOAD)
return false;
ImmutableSchedule schedule = getSchedule();
if(schedule.getNumOrders() <1){
//We end up here if all the train orders are deleted while a train
//is waiting for a full load.
return false;
}
TrainOrdersModel order = schedule.getOrder(schedule.getOrderToGoto());
if (order.stationId != stationId)
return false;
if (!order.waitUntilFull)
return false;
TrainModel train = getTrain();
return order.getConsist().equals(train.getConsist());
}
/**
* @return the location of the station the train is currently heading
* towards.
*/
public ImPoint getTarget() {
TrainModel train = (TrainModel) w.get(p, KEY.TRAINS, id);
int scheduleID = train.getScheduleID();
ImmutableSchedule schedule = (ImmutableSchedule) w.get(
p, KEY.TRAIN_SCHEDULES, scheduleID);
int stationNumber = schedule.getStationToGoto();
if (-1 == stationNumber) {
// There are no stations on the schedule.
return new ImPoint(0, 0);
}
StationModel station = (StationModel) w.get(p,
KEY.STATIONS, stationNumber);
return new ImPoint(station.x, station.y);
}
public HashSet<TrackSection> occupiedTrackSection(double time){
TrainMotion tm = findCurrentMotion(time);
PathOnTiles path = tm.getPath();
HashSet<TrackSection> sections = new HashSet<TrackSection>();
ImPoint start = path.getStart();
int x = start.x;
int y = start.y;
for (int i = 0; i < path.steps(); i++) {
Step s = path.getStep(i);
ImPoint tile = new ImPoint(x, y);
x+=s.deltaX;
y+=s.deltaY;
sections.add(new TrackSection(s, tile));
}
return sections;
}
public boolean isMoving(double time){
TrainMotion tm = findCurrentMotion(time);
double speed = tm.getSpeedAtEnd();
return speed != 0;
}
/** The space available on the train measured in cargo units.*/
public ImInts spaceAvailable(){
TrainModel train = (TrainModel) w.get(p, KEY.TRAINS, id);
ImmutableCargoBundle bundleOnTrain = (ImmutableCargoBundle) w.get(p,
KEY.CARGO_BUNDLES, train.getCargoBundleID());
return spaceAvailable2(w, bundleOnTrain, train.getConsist());
}
public static ImInts spaceAvailable2(ReadOnlyWorld row, ImmutableCargoBundle onTrain, ImInts consist){
// This array will store the amount of space available on the train for
// each cargo type.
final int NUM_CARGO_TYPES = row.size(SKEY.CARGO_TYPES);
int[] spaceAvailable = new int[NUM_CARGO_TYPES];
// First calculate the train's total capacity.
for (int j = 0; j < consist.size(); j++) {
int cargoType = consist.get(j);
spaceAvailable[cargoType] += WagonType.UNITS_OF_CARGO_PER_WAGON;
}
for (int cargoType = 0; cargoType < NUM_CARGO_TYPES; cargoType++) {
spaceAvailable[cargoType]= spaceAvailable[cargoType] - onTrain.getAmount(cargoType);
}
return new ImInts(spaceAvailable);
}
}

ScreenHandler

Full name: jfreerails.controller.ScreenHandler

Documentation

/**
* Handles going into fullscreen mode and setting buffer strategy etc.
*
* @author Luke
*/

Source Code

/**
* Handles going into fullscreen mode and setting buffer strategy etc.
*
* @author Luke
*/
final public class ScreenHandler {
private static final Logger logger = Logger.getLogger(ScreenHandler.class
.getName());
public static final int FULL_SCREEN = 0;
public static final int WINDOWED_MODE = 1;
public static final int FIXED_SIZE_WINDOWED_MODE = 2;
public final JFrame frame;
private BufferStrategy bufferStrategy;
private DisplayMode displayMode;
private final int mode;
private boolean isInUse = false;
/** Whether the window is minimised. */
private boolean isMinimised = false;
static GraphicsDevice device = GraphicsEnvironment
.getLocalGraphicsEnvironment().getDefaultScreenDevice();
public ScreenHandler(JFrame f, int mode, DisplayMode displayMode) {
this.displayMode = displayMode;
frame = f;
this.mode = mode;
}
public ScreenHandler(JFrame f, int mode) {
frame = f;
this.mode = mode;
}
private static void goFullScreen(JFrame frame, DisplayMode displayMode) {
setRepaintOffAndDisableDoubleBuffering(frame);
/*
* We need to make the frame not displayable before calling
* setUndecorated(true) otherwise a
* java.awt.IllegalComponentStateException will get thrown.
*/
if (frame.isDisplayable()) {
frame.dispose();
}
frame.setUndecorated(true);
device.setFullScreenWindow(frame);
if (device.isDisplayChangeSupported()) {
if (null == displayMode) {
displayMode = getBestDisplayMode();
}
logger.info("Setting display mode to: "
+ (new MyDisplayMode(displayMode).toString()));
device.setDisplayMode(displayMode);
}
frame.validate();
}
public synchronized void apply() {
switch (mode) {
case FULL_SCREEN: {
goFullScreen(frame, displayMode);
break;
}
case WINDOWED_MODE: {
// Some of the dialogue boxes do not get layed out properly if they
// are smaller than their
// minimum size. JFrameMinimumSizeEnforcer increases the size of the
// Jframe when its size falls
// below the specified size.
frame.addComponentListener(new JFrameMinimumSizeEnforcer(640, 480));
frame.setSize(640, 480);
frame.setVisible(true);
break;
}
case FIXED_SIZE_WINDOWED_MODE: {
/*
* We need to make the frame not displayable before calling
* setUndecorated(true) otherwise a
* java.awt.IllegalComponentStateException will get thrown.
*/
if (frame.isDisplayable()) {
frame.dispose();
}
frame.setUndecorated(true);
frame.setResizable(false);
frame.setSize(640, 480);
frame.setVisible(true);
break;
}
default:
throw new IllegalArgumentException(String.valueOf(mode));
}
createBufferStrategy();
frame.addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(java.awt.event.ComponentEvent evt) {
createBufferStrategy();
}
});
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowIconified(WindowEvent e) {
isMinimised = true;
}
@Override
public void windowDeiconified(WindowEvent e) {
isMinimised = false;
}
});
isInUse = true;
}
private synchronized void createBufferStrategy() {
// Use 2 backbuffers to avoid using too much VRAM.
frame.createBufferStrategy(2);
bufferStrategy = frame.getBufferStrategy();
setRepaintOffAndDisableDoubleBuffering(frame);
}
public synchronized Graphics getDrawGraphics() {
return bufferStrategy.getDrawGraphics();
}
public synchronized void swapScreens() {
if (!bufferStrategy.contentsLost()) {
bufferStrategy.show();
}
}
private static void setRepaintOffAndDisableDoubleBuffering(Component c) {
c.setIgnoreRepaint(true);
// Since we are using a buffer strategy we don't want Swing
// to double buffer any JComponents.
if (c instanceof JComponent) {
JComponent jComponent = (JComponent) c;
jComponent.setDoubleBuffered(false);
}
if (c instanceof java.awt.Container) {
Component[] children = ((Container) c).getComponents();
for (int i = 0; i < children.length; i++) {
setRepaintOffAndDisableDoubleBuffering(children[i]);
}
}
}
private static DisplayMode getBestDisplayMode() {
for (int x = 0; x < BEST_DISPLAY_MODES.length; x++) {
DisplayMode[] modes = device.getDisplayModes();
for (int i = 0; i < modes.length; i++) {
if (modes[i].getWidth() == BEST_DISPLAY_MODES[x].getWidth()
&& modes[i].getHeight() == BEST_DISPLAY_MODES[x]
.getHeight()
&& modes[i].getBitDepth() == BEST_DISPLAY_MODES[x]
.getBitDepth()) {
logger.fine("Best display mode is "
+ (new MyDisplayMode(BEST_DISPLAY_MODES[x]))
.toString());
return BEST_DISPLAY_MODES[x];
}
}
}
return null;
}
private static final DisplayMode[] BEST_DISPLAY_MODES = new DisplayMode[] {
new DisplayMode(640, 400, 8, 60),
new DisplayMode(800, 600, 16, 60),
new DisplayMode(1024, 768, 8, 60),
new DisplayMode(1024, 768, 16, 60), };
public synchronized boolean isMinimised() {
return isMinimised;
}
public synchronized boolean isInUse() {
return isInUse;
}
public synchronized static void exitFullScreenMode(){
device.setFullScreenWindow(null);
}
public boolean contentsRestored() {
return bufferStrategy.contentsRestored();
}
}

FinancialMoveProducer

Full name: jfreerails.controller.FinancialMoveProducer

Documentation

/**
* Not yet implemented
*
* @author Luke
*
*/

Source Code

/**
* Not yet implemented
*
* @author Luke
*
*/
public class FinancialMoveProducer {
public static final Money IPO_SHARE_PRICE = new Money(5);
public static final int SHARE_BUNDLE_SIZE = 10000;
public static final int IPO_SIZE = SHARE_BUNDLE_SIZE * 10;
FinancialMoveProducer(ReadOnlyWorld row) {
}
EconomicClimate worsen() {
return null;
}
EconomicClimate improve() {
return null;
}
}

TrackRenderer

Full name: experimental.TrackRenderer

Documentation

/**
* Provides methods that render track pieces.
*
* @see experimental.TrackTilesGenerator
* @author Luke Lindsay
*
*/

Source Code

/**
* Provides methods that render track pieces.
*
* @see experimental.TrackTilesGenerator
* @author Luke Lindsay
*
*/
public class TrackRenderer {
private final ImageManager imageManager = new ImageManagerImpl(
"/jfreerails/client/graphics/");
Color sleepersColor = new Color(118, 54, 36);
Color railsColor = new Color(118, 118, 118);
double sleeperLength = 6;
float sleeperWidth = 2f;
float targetSleeperGap = 2.5f;
float tileWidth = 30f;
float gauge = 3f;
BasicStroke rail = new BasicStroke(1f);
boolean doubleTrack = false;
float doubleTrackGap = 4f;
Image icon = null;
boolean tunnel = false;
void paintTrackConf(Graphics2D g2, TrackConfiguration conf) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Draw title
// String title = BinaryNumberFormatter.formatWithLowBitOnLeft(conf
// .get9bitTemplate(), 9);
// g.setColor(Color.BLACK);
// g.setFont(font);
//
// g.drawString(title, 10, 10);
Step[] directions = Step.getList();
List<CubicCurve2D.Double> sections = new ArrayList<CubicCurve2D.Double>();
int matches = 0;
for (int i = 0; i < directions.length - 2; i++) {
if (conf.contains(directions[i])) {
// System.out.println("\n"+directions[i]+" to ..");
int maxJ = Math.min(i + 7, directions.length);
for (int j = i + 2; j < maxJ; j++) {
// System.out.println(directions[j]);
if (conf.contains(directions[j])) {
Double toCurve = toCurve(directions[i], directions[j]);
if (doubleTrack) {
sections.add(createAdjacentCurve(toCurve,
doubleTrackGap, doubleTrackGap));
sections.add(createAdjacentCurve(toCurve,
-doubleTrackGap, -doubleTrackGap));
} else {
sections.add(toCurve);
}
matches++;
}
}
}
}
if (matches == 0) {
for (int i = 0; i < directions.length; i++) {
if (conf.contains(directions[i])) {
Double toCurve = toCurve(directions[i]);
if (doubleTrack) {
sections.add(createAdjacentCurve(toCurve,
doubleTrackGap, doubleTrackGap));
sections.add(createAdjacentCurve(toCurve,
-doubleTrackGap, -doubleTrackGap));
} else {
sections.add(toCurve);
}
}
}
}
paintTrack(g2, sections);
}
CubicCurve2D.Double toCurve(Step a) {
float halfTile = tileWidth / 2;
Point2D.Double start, end, one;
start = new Point2D.Double();
start.x = tileWidth + (halfTile * a.deltaX);
start.y = tileWidth + (halfTile * a.deltaY);
one = controlPoint(start);
end = new Point2D.Double(tileWidth, tileWidth);
CubicCurve2D.Double returnValue = new CubicCurve2D.Double();
returnValue.setCurve(start, one, one, end);
return returnValue;
}
CubicCurve2D.Double toCurve(Step a, Step b) {
float halfTile = tileWidth / 2;
Point2D.Double start, end, one, two;
start = new Point2D.Double();
start.x = tileWidth + (halfTile * a.deltaX);
start.y = tileWidth + (halfTile * a.deltaY);
one = controlPoint(start);
end = new Point2D.Double();
end.x = tileWidth + (halfTile * b.deltaX);
end.y = tileWidth + (halfTile * b.deltaY);
two = controlPoint(end);
CubicCurve2D.Double returnValue = new CubicCurve2D.Double();
returnValue.setCurve(start, one, two, end);
return returnValue;
}
void paintTrack(Graphics2D g, List<CubicCurve2D.Double> sections) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if (!tunnel) {
// Draw sleepers
g.setColor(sleepersColor);
for (CubicCurve2D.Double section : sections) {
BasicStroke dashed = getStroke4Curve(section);
g.setStroke(dashed);
g.draw(section);
}
g.setColor(railsColor);
} else {
g.setColor(Color.BLACK);
}
// Draw rails
g.setStroke(rail);
for (CubicCurve2D.Double section : sections) {
float halfGauge = gauge / 2;
CubicCurve2D.Double rail1 = createAdjacentCurve(section, halfGauge,
halfGauge);
CubicCurve2D.Double rail2 = createAdjacentCurve(section,
-halfGauge, -halfGauge);
g.draw(rail1);
g.draw(rail2);
}
}
/**
* Generates the Stroke used to draw the sleepers for track section
* represented by the specified curve.
*/
public BasicStroke getStroke4Curve(CubicCurve2D.Double curve) {
PathIterator fpt = curve.getPathIterator(new AffineTransform(), 0.01);
double length = 0;
double[] coords = new double[6];
double x, y;
fpt.currentSegment(coords);
double lastX = coords[0];
double lastY = coords[1];
for (; !fpt.isDone(); fpt.next()) {
fpt.currentSegment(coords);
x = coords[0];
y = coords[1];
double dx = x - lastX;
double dy = y - lastY;
length += Math.sqrt(dx * dx + dy * dy);
lastX = x;
lastY = y;
}
float sleepers = (float) length / (targetSleeperGap + sleeperWidth);
float sleeperCount = (int) sleepers;
float sleeperGap = (float) length / sleeperCount - sleeperWidth;
float dash1[] = { sleeperWidth, sleeperGap };
float phase = sleeperWidth + (sleeperGap / 2);
return new BasicStroke((float) sleeperLength, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f, dash1, phase);
}
public static Line2D.Double createParallelLine(Line2D.Double line,
double shift) {
Line2D.Double returnValue = new Line2D.Double(line.getP1(), line
.getP2());
double distance = line.getP1().distance(line.getP2());
double dRatio = shift / distance;
double dx = (line.x1 - line.x2) * dRatio;
double dy = (line.y1 - line.y2) * dRatio;
returnValue.x1 -= dy;
returnValue.y1 += dx;
returnValue.x2 -= dy;
returnValue.y2 += dx;
return returnValue;
}
public static CubicCurve2D.Double createAdjacentCurve(
CubicCurve2D.Double c, double shift1, double shift2) {
Line2D.Double line1 = new Line2D.Double(c.getX1(), c.getY1(), c
.getCtrlX1(), c.getCtrlY1());
Line2D.Double line2 = new Line2D.Double(c.getX2(), c.getY2(), c
.getCtrlX2(), c.getCtrlY2());
line1 = createParallelLine(line1, shift1);
line2 = createParallelLine(line2, -shift2);
return new CubicCurve2D.Double(line1.x1, line1.y1, line1.x2, line1.y2,
line2.x2, line2.y2, line2.x1, line2.y1);
}
private Point2D.Double controlPoint(Point2D.Double from) {
double weight = 0.3;
double x = from.getX() * weight + tileWidth * (1 - weight);
double y = from.getY() * weight + tileWidth * (1 - weight);
return new Point2D.Double(x, y);
}
void setIcon(String typeName) {
try {
String relativeFileName = "icons" + File.separator + typeName
+ ".png";
relativeFileName = relativeFileName.replace(' ', '_');
Image im = imageManager.getImage(relativeFileName);
icon = im;
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException(e);
}
}
}

SimpleComponentFactoryImpl2

Full name: experimental.SimpleComponentFactoryImpl2

Documentation

/**
* This GUIComponentFactory creates simple components that can be used to test
* the layout of the client jFrame without running the whole game.
*
* @author Luke Lindsay
*/

Source Code

/**
* This GUIComponentFactory creates simple components that can be used to test
* the layout of the client jFrame without running the whole game.
*
* @author Luke Lindsay
*/
public class SimpleComponentFactoryImpl2 implements
jfreerails.client.top.GUIComponentFactory {
private OverviewMapJComponent overviewMap;
private JScrollPane mainMapScrollPane1;
private MapViewJComponentConcrete mainMap;
private MainMapAndOverviewMapMediator mediator;
private Rectangle r = new Rectangle();
/** Creates new SimpleComponentFactoryImpl */
public SimpleComponentFactoryImpl2() {
}
public JMenu createBuildMenu() {
return new JMenu("Build");
}
public JMenu createGameMenu() {
return new JMenu("Game");
}
public JMenu createDisplayMenu() {
JMenu displayMenu = new JMenu("Display");
addMainmapzoomMenuItem(displayMenu, 5);
addMainmapzoomMenuItem(displayMenu, 10);
addOverviewmapzoomMenuItem(displayMenu, 0.2F);
addOverviewmapzoomMenuItem(displayMenu, 0.6F);
return displayMenu;
}
public JMenu createBrokerMenu() {
JMenu brokerMenu = new JMenu("Broker");
return brokerMenu;
}
private void addOverviewmapzoomMenuItem(JMenu displayMenu, final float scale) {
String menuItemName = "Set overview map scale=" + scale;
JMenuItem menuItem = new JMenuItem(menuItemName);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
overviewMap.setup(new BlankMapRenderer(scale));
}
});
displayMenu.add(menuItem);
}
private void addMainmapzoomMenuItem(JMenu displayMenu, final float scale) {
String menuItemName = "Set main map scale=" + scale;
JMenuItem menuItem = new JMenuItem(menuItemName);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Rectangle visRect = mainMap.getVisibleRect();
int oldWidth = mainMap.getWidth();
mainMap.setup(new BlankMapRenderer(scale));
int newWidth = mainMap.getPreferredSize().width;
int oldCenterX = visRect.x + (visRect.width / 2);
int newCenterX = oldCenterX * newWidth / oldWidth;
visRect.x = newCenterX - visRect.width / 2;
int oldCenterY = visRect.y + (visRect.height / 2);
int newCenterY = oldCenterY * newWidth / oldWidth;
visRect.y = newCenterY - visRect.height / 2;
/*
* LL: I'm not sure why the 'if' is necessary in the following,
* but the view does not center on the right spot without it.
*/
if (oldWidth < newWidth) {
mainMap.setSize(mainMap.getPreferredSize());
mainMap.scrollRectToVisible(visRect);
} else {
mainMap.scrollRectToVisible(visRect);
mainMap.setSize(mainMap.getPreferredSize());
}
}
});
displayMenu.add(menuItem);
}
public JScrollPane createMainMap() {
if (null == this.mainMap) {
// this.mainMap = new MapJPanel();
this.mainMap = new MapViewJComponentConcrete();
mainMapScrollPane1 = new JScrollPane();
mainMapScrollPane1.setViewportView(this.mainMap);
addMainMapAndOverviewMapMediatorIfNecessary();
}
return mainMapScrollPane1;
}
public JPanel createOverviewMap() {
if (null == this.overviewMap) {
// this.overviewMap = new OverviewMapJPanel();
this.overviewMap = new OverviewMapJComponent(r);
this.overviewMap.setup(new BlankMapRenderer(0.4F));
addMainMapAndOverviewMapMediatorIfNecessary();
}
return overviewMap;
// return new TestPanel();
}
private void addMainMapAndOverviewMapMediatorIfNecessary() {
if (this.mainMap != null && this.overviewMap != null
&& null == this.mediator) {
// Rectangle r = this.overviewMap.getMainMapVisibleRect();
this.mediator = new MainMapAndOverviewMapMediator(overviewMap,
mainMapScrollPane1.getViewport(), mainMap, r);
}
}
public JLabel createCashJLabel() {
return null;
}
public JLabel createDateJLabel() {
return null;
}
public JMenu createHelpMenu() {
return null;
}
public JTabbedPane createTrainsJTabPane() {
return null;
}
public JMenu createReportsMenu() {
// TODO Auto-generated method stub
return null;
}
}

DialogueBoxTester

Full name: experimental.DialogueBoxTester

Documentation

/**
* This class lets you test dialogue boxes without running the whole game.
*
* @author lindsal8
*
*/

Source Code

/**
* This class lets you test dialogue boxes without running the whole game.
*
* @author lindsal8
*
*/
public class DialogueBoxTester extends javax.swing.JFrame {
private static final long serialVersionUID = 4050764909631780659L;
private static final Player TEST_PLAYER = new Player("test player", 0);
private static final FreerailsPrincipal TEST_PRINCIPAL = TEST_PLAYER
.getPrincipal();
private final DialogueBoxController dialogueBoxController;
private World w;
private RenderersRoot vl;
private ModelRootImpl modelRoot;
private Action closeCurrentDialogue = new AbstractAction("Close") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
dialogueBoxController.closeContent();
}
};
;
private TrainDialogueJPanel trainDialogueJPanel = new TrainDialogueJPanel();
/** Creates new form TestGlassPanelMethod. */
private DialogueBoxTester() {
w = new WorldImpl(200, 200);
UntriedMoveReceiver dummyReceiver = new SimpleMoveReceiver(w);
modelRoot = new ModelRootImpl();
modelRoot.setMoveFork(new MoveChainFork());
modelRoot.setMoveReceiver(dummyReceiver);
WagonAndEngineTypesFactory wetf = new WagonAndEngineTypesFactory();
TileSetFactory tileFactory = new TileSetFactoryImpl();
tileFactory.addTerrainTileTypesList(w);
wetf.addTypesToWorld(w);
w.addPlayer(TEST_PLAYER);
try {
vl = new RenderersRootImpl(w, FreerailsProgressMonitor.NULL_INSTANCE);
} catch (IOException e) {
e.printStackTrace();
}
modelRoot.setup(w, TEST_PLAYER.getPrincipal());
ActionRoot actionRoot = new ActionRoot(modelRoot);
actionRoot.setup(modelRoot, vl);
dialogueBoxController = new DialogueBoxController(this, modelRoot);
actionRoot.setDialogueBoxController(dialogueBoxController);
dialogueBoxController.setDefaultFocusOwner(this);
int numberOfCargoTypes = w.size(SKEY.CARGO_TYPES);
StationModel bristol = new StationModel(10, 10, "Bristol",
numberOfCargoTypes, 0);
boolean[] demandArray = new boolean[numberOfCargoTypes];
// Make the stations demand all cargo..
for (int i = 0; i < demandArray.length; i++) {
demandArray[i] = true;
}
Demand4Cargo demand = new Demand4Cargo(demandArray);
bristol = new StationModel(bristol, demand);
w.add(TEST_PRINCIPAL, KEY.STATIONS, bristol);
w.add(TEST_PRINCIPAL, KEY.STATIONS, new StationModel(50, 100, "Bath",
numberOfCargoTypes, 0));
w.add(TEST_PRINCIPAL, KEY.STATIONS, new StationModel(40, 10, "Cardiff",
numberOfCargoTypes, 0));
w.add(TEST_PRINCIPAL, KEY.STATIONS, new StationModel(100, 10, "London",
numberOfCargoTypes, 0));
w.add(TEST_PRINCIPAL, KEY.STATIONS, new StationModel(90, 50, "Swansea",
numberOfCargoTypes, 0));
// Set up cargo bundle, for the purpose of this test code all the trains
// can share the
// same one.
MutableCargoBundle cb = new MutableCargoBundle();
cb.setAmount(new CargoBatch(0, 10, 10, 8, 0), 80);
cb.setAmount(new CargoBatch(0, 10, 10, 9, 0), 60);
cb.setAmount(new CargoBatch(1, 10, 10, 9, 0), 140);
cb.setAmount(new CargoBatch(3, 10, 10, 9, 0), 180);
cb.setAmount(new CargoBatch(5, 10, 10, 9, 0), 10);
w.add(TEST_PRINCIPAL, KEY.CARGO_BUNDLES, cb.toImmutableCargoBundle());
MutableSchedule schedule = new MutableSchedule();
TrainOrdersModel order = new TrainOrdersModel(0, new ImInts(0, 0, 0),
false, false);
TrainOrdersModel order2 = new TrainOrdersModel(1, new ImInts(1, 2, 0,
0, 0), true, false);
TrainOrdersModel order3 = new TrainOrdersModel(2, null, true, false);
schedule.setOrder(0, order);
schedule.setOrder(1, order2);
int scheduleID = w.add(TEST_PRINCIPAL, KEY.TRAIN_SCHEDULES, schedule
.toImmutableSchedule());
w.add(TEST_PRINCIPAL, KEY.TRAINS,
new TrainModel(0, new ImInts(0, 0), scheduleID));
schedule.setOrder(2, order2);
schedule.setOrder(3, order3);
scheduleID = w.add(TEST_PRINCIPAL, KEY.TRAIN_SCHEDULES,
schedule.toImmutableSchedule());
w.add(TEST_PRINCIPAL, KEY.TRAINS,
new TrainModel(1, new ImInts(1, 1), scheduleID));
schedule.setOrder(4, order2);
schedule.setOrderToGoto(3);
schedule.setPriorityOrders(order);
scheduleID = w.add(TEST_PRINCIPAL, KEY.TRAIN_SCHEDULES,
schedule.toImmutableSchedule());
w.add(TEST_PRINCIPAL, KEY.TRAINS,
new TrainModel(0, new ImInts(1, 2, 0), scheduleID));
final MyGlassPanel glassPanel = new MyGlassPanel();
dialogueBoxController.setup(modelRoot, vl);
initComponents();
glassPanel.setSize(800, 600);
this.addComponentListener(new JFrameMinimumSizeEnforcer(640, 480));
this.setSize(640, 480);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
jLabel1 = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
show = new javax.swing.JMenu();
showBrokerScreen = new javax.swing.JMenuItem();
selectEngine = new javax.swing.JMenuItem();
selectWagons = new javax.swing.JMenuItem();
selectTrainOrders = new javax.swing.JMenuItem();
showControls = new javax.swing.JMenuItem();
showTerrainInfo = new javax.swing.JMenuItem();
showStationInfo = new javax.swing.JMenuItem();
showTrainList = new javax.swing.JMenuItem();
showReportBug = new javax.swing.JMenuItem();
throwException = new javax.swing.JMenuItem();
showCargoWaitingAndDemand = new javax.swing.JMenuItem();
showJavaSystemProperties = new javax.swing.JMenuItem();
showNetworthGraph = new javax.swing.JMenuItem();
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/jfreerails/data/south_america.png")));
jLabel1.setText("Press Esc to close dialogue boxes");
jLabel1.setMinimumSize(new java.awt.Dimension(640, 480));
jLabel1.setPreferredSize(new java.awt.Dimension(640, 480));
getContentPane().add(jLabel1, java.awt.BorderLayout.CENTER);
show.setText("Show");
showBrokerScreen.setText("Broker Screen");
showBrokerScreen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newspaperActionPerformed(evt);
}
});
show.add(showBrokerScreen);
selectEngine.setText("Select Engine");
selectEngine.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectEngineActionPerformed(evt);
}
});
show.add(selectEngine);
selectWagons.setText("Select Wagons");
selectWagons.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectWagonsActionPerformed(evt);
}
});
show.add(selectWagons);
selectTrainOrders.setText("Train Orders");
selectTrainOrders
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectTrainOrdersActionPerformed(evt);
}
});
show.add(selectTrainOrders);
showControls.setText("Show game controls");
showControls.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showControlsActionPerformed(evt);
}
});
show.add(showControls);
showTerrainInfo.setText("Show Terrain Info");
showTerrainInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showTerrainInfoActionPerformed(evt);
}
});
show.add(showTerrainInfo);
showStationInfo.setText("Show Station Info");
showStationInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showStationInfoActionPerformed(evt);
}
});
show.add(showStationInfo);
showTrainList.setText("Train List");
showTrainList.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showTrainListActionPerformed(evt);
}
});
show.add(showTrainList);
showCargoWaitingAndDemand.setText("Cargo waiting & demand");
showCargoWaitingAndDemand
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showCargoWaitingAndDemandActionPerformed(evt);
}
});
show.add(showCargoWaitingAndDemand);
showJavaSystemProperties.setText("Java System Properties");
showJavaSystemProperties
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showJavaSystemPropertiesActionPerformed(evt);
}
});
throwException.setText("Throw Exception");
throwException.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
throw new IllegalArgumentException();
}
});
show.add(showJavaSystemProperties);
showNetworthGraph.setText("Show networth graph");
showNetworthGraph
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showNetworthGraphActionPerformed(evt);
}
});
show.add(showNetworthGraph);
showReportBug.setText("Report Bug");
showReportBug
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showReportBug();
}
});
show.add(showReportBug);
jMenuBar1.add(show);
setJMenuBar(jMenuBar1);
}// GEN-END:initComponents
private void showNetworthGraphActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showNetworthGraphActionPerformed
dialogueBoxController.showNetworthGraph();
}// GEN-LAST:event_showNetworthGraphActionPerformed
private void showJavaSystemPropertiesActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showJavaSystemPropertiesActionPerformed
// Add your handling code here:
String s = ShowJavaProperties.getPropertiesHtmlString();
HtmlJPanel htmlPanel = new HtmlJPanel(s);
htmlPanel.setup(modelRoot, vl, closeCurrentDialogue);
dialogueBoxController.showContent(htmlPanel);
}// GEN-LAST:event_showJavaSystemPropertiesActionPerformed
private void formKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_formKeyPressed
if (java.awt.event.KeyEvent.VK_ESCAPE == evt.getKeyCode()) {
dialogueBoxController.closeContent();
}
}// GEN-LAST:event_formKeyPressed
private void showCargoWaitingAndDemandActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showCargoWaitingAndDemandActionPerformed
// Add your handling code here:
CargoWaitingAndDemandedJPanel panel = new CargoWaitingAndDemandedJPanel();
panel.setup(modelRoot, vl, closeCurrentDialogue);
int newStationID = 0;
panel.display(newStationID);
dialogueBoxController.showContent(panel);
}// GEN-LAST:event_showCargoWaitingAndDemandActionPerformed
private void showTrainListActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showTrainListActionPerformed
// Add your handling code here:
dialogueBoxController.showTrainList();
}// GEN-LAST:event_showTrainListActionPerformed
private void showStationInfoActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showStationInfoActionPerformed
// Add your handling code here:
int stationNumber = 0;
dialogueBoxController.showStationInfo(stationNumber);
}// GEN-LAST:event_showStationInfoActionPerformed
private void showTerrainInfoActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showTerrainInfoActionPerformed
// Add your handling code here:
int terrainType = 0;
dialogueBoxController.showTerrainInfo(terrainType);
}// GEN-LAST:event_showTerrainInfoActionPerformed
private void showControlsActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showControlsActionPerformed
// Add your handling code here:
dialogueBoxController.showGameControls();
}// GEN-LAST:event_showControlsActionPerformed
private void selectTrainOrdersActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_selectTrainOrdersActionPerformed
// Add your handling code here:
trainDialogueJPanel.setup(modelRoot, vl, closeCurrentDialogue);
trainDialogueJPanel.display(0);
dialogueBoxController.showContent(trainDialogueJPanel);
}// GEN-LAST:event_selectTrainOrdersActionPerformed
private void selectWagonsActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_selectWagonsActionPerformed
// Add your handling code here:
dialogueBoxController.showSelectWagons();
}// GEN-LAST:event_selectWagonsActionPerformed
private void selectEngineActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_selectEngineActionPerformed
// Add your handling code here:
dialogueBoxController.showSelectEngine();
}// GEN-LAST:event_selectEngineActionPerformed
private void newspaperActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_newspaperActionPerformed
// Add your handling code here:
dialogueBoxController.showBrokerScreen();
//dialogueBoxController.showNewspaper("New headline!");
}// GEN-LAST:event_newspaperActionPerformed
/** Exit the Application. */
private void exitForm(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_exitForm
System.exit(0);
}// GEN-LAST:event_exitForm
public static void main(String args[]) {
DialogueBoxTester test = new DialogueBoxTester();
test.setVisible(true);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
javax.swing.JLabel jLabel1;
javax.swing.JMenuBar jMenuBar1;
javax.swing.JMenuItem showBrokerScreen;
javax.swing.JMenuItem selectEngine;
javax.swing.JMenuItem selectTrainOrders;
javax.swing.JMenuItem selectWagons;
javax.swing.JMenu show;
javax.swing.JMenuItem showCargoWaitingAndDemand;
javax.swing.JMenuItem showControls;
javax.swing.JMenuItem showJavaSystemProperties;
javax.swing.JMenuItem showNetworthGraph;
javax.swing.JMenuItem showStationInfo;
javax.swing.JMenuItem showTerrainInfo;
javax.swing.JMenuItem showTrainList;
javax.swing.JMenuItem showReportBug;
javax.swing.JMenuItem throwException;
// End of variables declaration//GEN-END:variables
}

ExptWriteToBuffer

Full name: experimental.ExptWriteToBuffer

Documentation

/**
* Experiment to try out reading and writing to a buffer to test serialization
* code.
*
* @author Luke
*
*/

Source Code

/**
* Experiment to try out reading and writing to a buffer to test serialization
* code.
*
* @author Luke
*
*/
public class ExptWriteToBuffer {
private static final Logger logger = Logger
.getLogger(ExptWriteToBuffer.class.getName());
public static void main(String[] args) {
try {
Point p = new Point(10, 10);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objectOut = new ObjectOutputStream(out);
objectOut.writeObject(p);
objectOut.flush();
byte[] bytes = out.toByteArray();
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
ObjectInputStream objectIn = new ObjectInputStream(in);
Object o = objectIn.readObject();
Point p2 = (Point) o;
if (p.equals(p2)) {
logger.info("The two objects are equal!");
} else {
logger.info("The two objects are not equal!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Methods

AnimationExpt

Full name: experimental.AnimationExpt

Documentation

/**
* This class tests that the game loop and screen handler are working correctly.
* All it does is display the current time in ms and display the number of
* frames per second.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* This class tests that the game loop and screen handler are working correctly.
* All it does is display the current time in ms and display the number of
* frames per second.
*
* @author Luke Lindsay
*
*/
public class AnimationExpt extends JComponent {
private static final long serialVersionUID = 3690191057862473264L;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
long l = System.currentTimeMillis();
String str = String.valueOf(l);
g.drawString(str, 100, 100);
}
public static void main(String[] args) {
System.setProperty("SHOWFPS", "true");
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.getContentPane().add(new AnimationExpt());
ScreenHandler screenHandler = new ScreenHandler(f,
ScreenHandler.WINDOWED_MODE);
screenHandler.apply();
GameLoop gameLoop = new GameLoop(screenHandler);
Thread t = new Thread(gameLoop);
t.start();
}
}

GenerateDependenciesXmlAndHtml

Full name: experimental.GenerateDependenciesXmlAndHtml

Documentation

/**
* This class generates an ant script that checks the dependencies between
* packages and also generates an html page that illustrates the allowed
* dependencies. The checkdep target on the generated ant script tests the
* dependencies of packages. It does this by copying the contents of the package
* in question together with the contents of the packages it is allowed to
* depend on to a temporary directory, then compiling the contents of the
* package. If the packaged depends on classes other than those contained in the
* packages it is allowed to depend on, the compile will fail.
*
* @author Luke
*
*/

Source Code

/**
* This class generates an ant script that checks the dependencies between
* packages and also generates an html page that illustrates the allowed
* dependencies. The checkdep target on the generated ant script tests the
* dependencies of packages. It does this by copying the contents of the package
* in question together with the contents of the packages it is allowed to
* depend on to a temporary directory, then compiling the contents of the
* package. If the packaged depends on classes other than those contained in the
* packages it is allowed to depend on, the compile will fail.
*
* @author Luke
*
*/
public class GenerateDependenciesXmlAndHtml {
private static final Logger logger = Logger
.getLogger(GenerateDependenciesXmlAndHtml.class.getName());
private PrintWriter xmlWriter;
private PrintWriter htmlWriter;
private ArrayList<String> packages = new ArrayList<String>();
private boolean started = false;
private boolean startedBlock = false;
private String sig;
public static void main(String[] args) {
try {
new GenerateDependenciesXmlAndHtml("checkdep.xml", "src"
+ File.separator + "docs" + File.separator
+ "dependencies.html");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private GenerateDependenciesXmlAndHtml(String xmlFilename,
String htmlFilename) throws FileNotFoundException {
Date d = new Date();
sig = this.getClass().getName() + " on " + d;
// Setup writers
File xmlFile = new File(xmlFilename);
xmlWriter = new PrintWriter(new FileOutputStream(xmlFile));
File htmlFile = new File(htmlFilename);
htmlWriter = new PrintWriter(new FileOutputStream(htmlFilename));
String[] basePackages = { "jfreerails/util/*" };
start();
startBlock("All");
add(basePackages);
add("jfreerails/world/**/*");
add("jfreerails/move/**/*");
add("jfreerails/controller/*");
add("jfreerails/network/*");
add(new String[] { "jfreerails/server/**/*", "jfreerails/client/**/*" });
add("jfreerails/launcher/**/*");
add("jfreerails/experimental/**/*");
endBlock();
startBlock("World");
add(basePackages);
add("jfreerails/world/common/*");
add(new String[] { "jfreerails/world/terrain/*",
"jfreerails/world/cargo/*", "jfreerails/world/train/*",
"jfreerails/world/station/*" });
add("jfreerails/world/track/*");
add("jfreerails/world/accounts/*");
add("jfreerails/world/player/*");
add("jfreerails/world/top/*");
endBlock();
startBlock("Server");
add(basePackages);
add("jfreerails/world/**/*");
add("jfreerails/move/**/*");
add("jfreerails/controller/*");
add("jfreerails/network/*");
add("jfreerails/server/common/*");
add("jfreerails/server/parser/*");
add("jfreerails/server/*");
endBlock();
startBlock("Client");
add(basePackages);
add("jfreerails/world/**/*");
add("jfreerails/move/**/*");
add("jfreerails/controller/*");
add("jfreerails/network/*");
add("jfreerails/client/common/*");
add("jfreerails/client/renderer/*");
add("jfreerails/client/view/*");
add("jfreerails/client/top/*");
endBlock();
finish();
xmlWriter.flush();
htmlWriter.flush();
logger.info(sig);
logger.info("Wrote " + xmlFile);
logger.info("Wrote " + htmlFile);
}
private void start() {
assert !started;
startXml();
htmlWriter.write("<html>\n");
htmlWriter.write("<title>Dependencies between packages</title>\n");
htmlWriter.write("<p><code>This file was generate by " + sig
+ "</code></p>\n");
htmlWriter.write("<h1>Dependencies between packages</h1>\n");
htmlWriter
.write("<p>The figures below show the dependencies: packages may only depend, i.e. import classes and interfaces, from packages below.</p>\n");
started = true;
}
private void startBlock(String blockName) {
assert started;
assert !startedBlock;
startedBlock = true;
htmlWriter.write("<h2>" + blockName + "</h2>");
xmlWriter
.write("\n\t\t<!-- Setup the directory where the legal dependencies are stored -->\n");
xmlWriter.write("\t\t<delete dir=\"dependencies\" />\n");
xmlWriter.write("\t\t<mkdir dir=\"dependencies\" />\n");
}
private void endBlock() {
assert started;
assert startedBlock;
htmlWriter
.write("<table width=\"100%\" border=\"1\" cellpadding=\"10\" cellspacing=\"10\" bordercolor=\"#333333\" bgcolor=\"#FFFFFF\">\n");
for (int i = packages.size() - 1; i >= 0; i--) {
String packageName = packages.get(i);
htmlWriter.write("<tr bgcolor=\"#FFCCCC\"> \n");
htmlWriter.write("<td height=\"50\" bgcolor=\"#FFCC66\">"
+ packageName + "</td>\n");
htmlWriter.write("</tr>\n");
}
htmlWriter.write("</table>\n");
packages.clear();
xmlWriter.write("\n\t\t<!-- End Block -->\n");
xmlWriter.write("\t\t<echo message=\"End Block\"/>\n");
startedBlock = false;
}
private void startXml() {
// Start the file.
xmlWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
xmlWriter
.write("<project basedir=\".\" default=\"checkdep\" name=\"checkdep\">\n");
xmlWriter.write("\t<description>This ant script was generated by "
+ sig
+ " to check the dependencies for jfreerails.</description>\n");
// Set the properties.
// Add the compile target.
xmlWriter
.write("\n\t<target description=\"Build everything except JUnit test-classes\" name=\"compile\">\n");
xmlWriter.write("\t\t<mkdir dir=\"build\" />\n");
xmlWriter
.write("\t\t<javac destdir=\"build\" fork=\"true\" srcdir=\"src\" source=\"1.5\">\n");
xmlWriter.write("\t\t\t<exclude name=\"**/*Test.java\" />\n");
xmlWriter.write("\t\t </javac>\n");
xmlWriter.write("\t</target>\n");
// Start the check depend target.
xmlWriter
.write("\n\n\t<target depends=\"compile\" description=\"Tests whether dependencies between packages conform to the rules defined in this target\" name=\"checkdep\">\n");
}
private void add(String packageName) {
add(new String[] { packageName });
}
private void add(String[] packageNames) {
assert started;
assert startedBlock;
String packagesString = "";
for (int i = packageNames.length - 1; i > 0; i--) {
packagesString += convertToPackageName(packageNames[i]) + ", ";
}
packagesString += " " + convertToPackageName(packageNames[0]);
// The html writer will use this later.
packages.add(packagesString);
xmlWriter.write("\n\t\t<!-- New row: " + packagesString + " -->\n");
xmlWriter.write("\t\t<echo message=\"New row: " + packagesString
+ "\"/>\n");
// Include the source files we are going to compile.
for (String packageName : packageNames) {
xmlWriter.write("\t\t<echo message=\"Check dependencies for "
+ packageName + "\"/>\n");
xmlWriter.write("\t\t<delete dir=\"temp\" />\n");
xmlWriter.write("\t\t<mkdir dir=\"temp\" />\n");
// First copy the files we are testing.
xmlWriter.write("\t\t<copy todir=\"temp\">\n");
xmlWriter.write("\t\t<fileset dir=\"src\">\n");
xmlWriter.write("\t\t\t<include name=\"" + packageName
+ ".java\" />\n");
// Exclude unit tests.
xmlWriter.write("\t\t\t<exclude name=\"**/*Test.java\" />\n");
xmlWriter.write("\t\t</fileset>\n");
xmlWriter.write("\t\t</copy>\n");
xmlWriter
.write("\t\t<javac fork=\"true\" srcdir=\"temp\" source=\"1.5\" classpath=\"dependencies\">\n");
// Include the files we are going to compile.
xmlWriter.write("\t\t\t<include name=\"" + packageName
+ ".java\" />\n");
xmlWriter.write("\t\t</javac>\n");
xmlWriter.write("\t\t<delete dir=\"temp\" />\n");
}
// Copy the files we have just tested to the dependencies directory.
xmlWriter.write("\t\t<copy todir=\"dependencies\">\n");
xmlWriter.write("\t\t<fileset dir=\"build\">\n");
for (int i = 0; i < packageNames.length; i++) {
xmlWriter.write("\t\t\t<include name=\"" + packageNames[i]
+ ".class\" />\n");
}
xmlWriter.write("\t\t\t<exclude name=\"**/*Test.class\" />\n");
xmlWriter.write("\t\t</fileset>\n");
xmlWriter.write("\t\t</copy>\n");
}
private String convertToPackageName(String packagesString) {
if (!isPackageNameOk(packagesString)) {
throw new IllegalArgumentException(packagesString);
}
packagesString = packagesString.replace('/', '.');
/*
* Remove the last two characters, so that jfreerails.world.**.* - >
* jfreerails.world.** and jfreerails.util.* -> jfreerails.util
*/
packagesString = packagesString.substring(0,
packagesString.length() - 2);
return packagesString;
}
static boolean isPackageNameOk(String s) {
return s.matches("(([a-zA-Z]*)/)*\\*")
|| s.matches("(([a-zA-Z]*)/)*\\*\\*/\\*");
}
private void finish() {
assert started;
assert !startedBlock;
// finish the file.
xmlWriter.write("\t\t<delete dir=\"temp\" />\n");
xmlWriter.write("\t\t<delete dir=\"dependencies\" />\n");
xmlWriter.write("\t</target>\n");
xmlWriter.write("</project>\n");
htmlWriter.write("</html>\n");
started = false;
}
}

SimpleMoveReceiver

Full name: experimental.SimpleMoveReceiver

Documentation

/**
* An UntriedMoveReceiver that executes moves on the world object passed to its
* constructor.
*
* @author Luke
*
*/

Source Code

/**
* An UntriedMoveReceiver that executes moves on the world object passed to its
* constructor.
*
* @author Luke
*
*/
public final class SimpleMoveReceiver implements UntriedMoveReceiver {
private final World w;
public SimpleMoveReceiver(World w) {
this.w = w;
if (null == w)
throw new NullPointerException();
}
public MoveStatus tryDoMove(Move move) {
return move.tryDoMove(w, Player.AUTHORITATIVE);
}
public void processMove(Move move) {
move.doMove(w, Player.AUTHORITATIVE);
}
public void processPreMove(PreMove pm) {
processMove(pm.generateMove(w));
}
}

CheckFreerailsSerializableClasses

Full name: experimental.CheckFreerailsSerializableClasses

Documentation

/** Checks that all class that implement FreerailsSerializable are immutable and override equals and hashcode.
*
*
*/

Source Code

/** Checks that all class that implement FreerailsSerializable are immutable and override equals and hashcode.
*
*
*/
public class CheckFreerailsSerializableClasses {
static final HashSet<Class> immutableTypes = new HashSet<Class>();
static final HashSet<Class> mutableTypes = new HashSet<Class>();
static Logger logger = Logger.getLogger(CheckFreerailsSerializableClasses.class
.getName());
public static void main(String[] args) {
immutableTypes.clear();
mutableTypes.clear();
immutableTypes.add(String.class);
// Class clazz = StationModel.class;
// System.err.println(overridesHashCodeAndEquals(clazz));
// System.out.println(clazz.isAnnotationPresent(InstanceControlled.class));
// Annotation[] ans = clazz.getAnnotations();
// for (Annotation an : ans) {
// System.err.println(an);
// }
// System.err.println(checkFields(clazz));
testAllClasses();
for (Class c : mutableTypes) {
System.err.println(c.getName());
}
}
static boolean checkFields(Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
boolean okSoFar = true;
boolean assertImmutable = clazz.isAnnotationPresent(Immutable.class);
for (Field field : fields) {
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers)) {
logger.fine("Skipping static field " + field.getName());
continue;
}
Class<?> type = field.getType();
if (type.isPrimitive()) {
continue;
}
// if(!Modifier.isPrivate(modifiers)){
// System.err.println(clazz.getName()+field.getName()+" should be
// private!");
// okSoFar = false;
// }
if (!FreerailsSerializable.class.isAssignableFrom(type)
&& !assertImmutable) {
if (!immutableTypes.contains(type) && !type.isEnum()
&& !type.isAnnotationPresent(Immutable.class)) {
System.err.println(clazz.getName() + "." + field.getName()
+ " {" + type.getName()
+ "} might not be immutable!");
okSoFar = false;
if (!type.isArray())
mutableTypes.add(type);
}
}
}
return okSoFar;
}
@SuppressWarnings("unchecked")
static void testAllClasses() {
ClassLocater locater = new ClassLocater();
Class[] classes = locater.getSubclassesOf(FreerailsSerializable.class);
int classesWithProblems = 0;
for (Class clazz : classes) {
if (clazz.isInterface()) {
logger.fine("Skipping interface " + clazz.getName());
continue;
}
int mods = clazz.getModifiers();
if ((mods & Modifier.ABSTRACT) != 0) {
logger.fine("Skipping abstract class " + clazz.getName());
continue;
}
if (clazz.isAnnotationPresent(InstanceControlled.class)) {
logger.fine("Skipping InstanceControlled class "
+ clazz.getName());
continue;
}
boolean b = overridesHashCodeAndEquals(clazz);
b = b && checkFields(clazz);
if (!b) {
classesWithProblems++;
}
}
System.err.println(classes.length + " classes checked, "
+ classesWithProblems + " have problems");
}
static boolean overridesHashCodeAndEquals(Class clazz) {
try {
boolean okSoFar = true;
Method equals = clazz.getMethod("equals", Object.class);
if (equals.getDeclaringClass().equals(Object.class)) {
System.err.println(clazz.getName() + " does not override "
+ equals.getName());
okSoFar = false;
}
Method hashCode = clazz.getMethod("hashCode");
if (hashCode.getDeclaringClass().equals(Object.class)) {
System.err.println(clazz.getName() + " does not override "
+ hashCode.getName());
okSoFar = false;
}
return okSoFar;
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}

TrackTilesGenerator

Full name: experimental.TrackTilesGenerator

Documentation

/**
* Generates track graphic image files.
*
* @author Luke
*/

Source Code

/**
* Generates track graphic image files.
*
* @author Luke
*/
public class TrackTilesGenerator extends JPanel {
private static final long serialVersionUID = 3618982273966487859L;
public static void main(String[] args) {
JFrame frame = new JFrame();
JScrollPane scrollPane = new JScrollPane();
frame.add(scrollPane);
TrackTilesGenerator trackTilesGenerator = new TrackTilesGenerator();
trackTilesGenerator.setPreferredSize(trackTilesGenerator
.getSize4Panel());
scrollPane.setViewportView(trackTilesGenerator);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private final ImageManager imageManager = new ImageManagerImpl(
"/experimental/", "/experimental/");
private List<TrackRule> rules;
private TrackRenderer tr;
CubicCurve2D.Double[] track;
public TrackTilesGenerator() {
Point2D.Double start, end, one, two;
track = new CubicCurve2D.Double[3];
track[0] = new CubicCurve2D.Double();
start = new Point2D.Double(150, 300);
end = new Point2D.Double(450, 150);
one = controlPoint(start);
two = controlPoint(end);
track[0].setCurve(start, one, two, end);
track[1] = TrackRenderer.createAdjacentCurve(track[0], 0, 0);
track[2] = TrackRenderer.createAdjacentCurve(track[0], -60, -60);
tr = new TrackRenderer();
URL track_xml_url = OldWorldImpl.class
.getResource("/jfreerails/data/track_tiles.xml");
Track_TilesHandlerImpl trackSetFactory = new Track_TilesHandlerImpl(
track_xml_url);
rules = trackSetFactory.getRuleList();
generateTiles();
}
private Point2D.Double controlPoint(Point2D.Double from) {
double weight = 0.3;
double x = from.getX() * weight + 300 * (1 - weight);
double y = from.getY() * weight + 300 * (1 - weight);
return new Point2D.Double(x, y);
}
private void generateTiles() {
for (TrackRule rule : rules) {
TrackRule.TrackCategories category = rule.getCategory();
Image icon;
if (category.equals(TrackRule.TrackCategories.bridge)
|| category.equals(TrackRule.TrackCategories.station)) {
tr.setIcon(rule.getTypeName());
icon = tr.icon;
} else {
icon = null;
}
if (category.equals(TrackRule.TrackCategories.tunnel)) {
tr.tunnel = true;
} else {
tr.tunnel = false;
}
tr.doubleTrack = rule.isDouble();
for (int i = 0; i < 512; i++) {
if (rule.testTrackPieceLegality(i)) {
String fileName = TrackPieceRendererImpl.generateFilename(
i, rule.getTypeName());
TrackConfiguration conf = TrackConfiguration
.from9bitTemplate(i);
Image smallImage = imageManager.newBlankImage(60, 60);
Graphics2D g2 = (Graphics2D) smallImage.getGraphics();
tr.paintTrackConf(g2, conf);
// Draw icon. Used for bridges and stations.
if (null != icon) {
int x = 30 - icon.getWidth(null) / 2;
int y = 30 - icon.getHeight(null) / 2;
g2.drawImage(icon, x, y, null);
}
g2.dispose();
imageManager.setImage(fileName, smallImage);
}
}
}
try {
imageManager.writeAllImages();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Dimension getSize4Panel() {
int height = 90 * rules.size();
int width = 0;
int lastWidth = 0;
for (TrackRule rule : rules) {
width = Math.max(width, lastWidth);
lastWidth = 0;
Iterator<TrackConfiguration> it = rule
.getLegalConfigurationsIterator();
while (it.hasNext()) {
lastWidth += 60;
}
}
return new Dimension(width, height);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (TrackRule rule : rules) {
String typeName = rule.getTypeName();
typeName += rule.isDouble() ? " (Double) " : " (Single)";
g.drawString(typeName, 10, 10);
g.translate(0, 30);
Graphics2D g2 = (Graphics2D) g.create();
for (int i = 0; i < 512; i++) {
if (rule.testTrackPieceLegality(i)) {
String fileName = TrackPieceRendererImpl.generateFilename(
i, rule.getTypeName());
Image tile;
try {
tile = imageManager.getImage(fileName);
g2.drawImage(tile, 0, 0, null);
g2.translate(60, 0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
g.translate(0, 60);
}
}
}

LineDrawTrackPieceView

Full name: experimental.LineDrawTrackPieceView

Documentation

/**
* This TrackPieceRenderer renders track pieces by drawing lines so avoids the
* need to load images.
*
* @author Luke Lindsay
*/

Source Code

/**
* This TrackPieceRenderer renders track pieces by drawing lines so avoids the
* need to load images.
*
* @author Luke Lindsay
*/
public class LineDrawTrackPieceView implements
jfreerails.client.renderer.TrackPieceRenderer {
private int[] xx = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };
private int[] yy = { -1, -1, -1, 0, 0, 0, 1, 1, 1 };
public java.awt.Image getTrackPieceIcon(int trackTemplate) {
return null;
}
public void drawTrackPieceIcon(int trackTemplate, java.awt.Graphics g,
int x, int y, java.awt.Dimension tileSize) {
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new java.awt.BasicStroke(8.0f));
g2.setColor(java.awt.Color.red);
if (0 != trackTemplate) {
int drawX = x * tileSize.width;
int drawY = y * tileSize.height;
// g.drawLine(drawX-10,drawY-10,drawX+10,drawY+10);
for (int i = 0; i < 9; i++) {
if ((trackTemplate & (1 << i)) == (1 << i)) {
g2.drawLine(drawX + 15, drawY + 15,
drawX + 15 + 15 * xx[i], drawY + 15 + 15 * yy[i]);
}
}
}
}
public void dumpImages(ImageManager imageManager) {
// TODO Auto-generated method stub
}
}

TestLogging

Full name: experimental.TestLogging

Documentation

/**
* <p>
* Used to test the logging configuration.
* </p>
* <p>
* Usage:<code> java -Djava.util.logging.config.file=logging.properties experimental.TestLogging</code>
* </p>
* <p>
* Make sure <code>logging.properties</code> is in the working directory.
* </p>
*
* @author Luke
*/

Source Code

/**
* <p>
* Used to test the logging configuration.
* </p>
* <p>
* Usage:<code> java -Djava.util.logging.config.file=logging.properties experimental.TestLogging</code>
* </p>
* <p>
* Make sure <code>logging.properties</code> is in the working directory.
* </p>
*
* @author Luke
*/
public class TestLogging {
public static void main(String[] args) {
Logger logger1 = Logger.getLogger(TestLogging.class.getName());
logger1.info("Logging properties file: "
+ System.getProperty("java.util.logging.config.file"));
logger1.severe("Hello severe logging");
logger1.warning("Hello warning logging");
logger1.info("Hello info logging");
logger1.fine("Hello fine logging");
logger1.finer("Hello finer logging");
logger1.finest("Hello finest logging");
}
}

Methods

TrainMotionExpt

Full name: experimental.TrainMotionExpt

Documentation

/**
* This class is a visual test for the train movement code.
*
* TODO: Update the trains position when necessary. Make the train stop at
* intervals, and slowly accelerate.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* This class is a visual test for the train movement code.
*
* TODO: Update the trains position when necessary. Make the train stop at
* intervals, and slowly accelerate.
*
* @author Luke Lindsay
*
*/
public class TrainMotionExpt extends JComponent {
private static final long serialVersionUID = 3690191057862473264L;
private final World world;
private final FreerailsPrincipal principal;
private double finishTime = 0;
private long startTime;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Shade tiles with track..
g.setColor(Color.GREEN);
for (int x = 0; x < world.getMapWidth(); x++) {
for (int y = 0; y < world.getMapHeight(); y++) {
FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
if (tile.getTrackPiece().getTrackTypeID() != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
int w = Step.TILE_DIAMETER;
int h = Step.TILE_DIAMETER;
g.drawRect(x * Step.TILE_DIAMETER, y * Step.TILE_DIAMETER,
w, h);
}
}
}
long l = System.currentTimeMillis() - startTime;
double ticks = (double) l / 1000;
while (ticks > finishTime) {
updateTrainPosition();
}
ActivityIterator ai = world.getActivities(principal, 0);
while (ai.getFinishTime() < ticks && ai.hasNext()) {
ai.nextActivity();
}
double t = Math.min(ticks, ai.getFinishTime());
t = t - ai.getStartTime();
TrainMotion motion = (TrainMotion) ai.getActivity();
TrainPositionOnMap pos = (TrainPositionOnMap) ai.getState(ticks);
PathOnTiles pathOT = motion.getPath();
Iterator<ImPoint> it = pathOT.tiles();
while (it.hasNext()) {
ImPoint tile = it.next();
int x = tile.x * Step.TILE_DIAMETER;
int y = tile.y * Step.TILE_DIAMETER;
int w = Step.TILE_DIAMETER;
int h = Step.TILE_DIAMETER;
g.setColor(Color.WHITE);
g.fillRect(x, y, w, h);
g.setColor(Color.DARK_GRAY);
g.drawRect(x, y, w, h);
}
pathOT = motion.getTiles(t);
it = pathOT.tiles();
while (it.hasNext()) {
ImPoint tile = it.next();
int x = tile.x * Step.TILE_DIAMETER;
int y = tile.y * Step.TILE_DIAMETER;
int w = Step.TILE_DIAMETER;
int h = Step.TILE_DIAMETER;
g.setColor(Color.LIGHT_GRAY);
g.fillRect(x, y, w, h);
g.setColor(Color.DARK_GRAY);
g.drawRect(x, y, w, h);
}
g.setColor(Color.BLACK);
IntLine line = new IntLine();
FreerailsPathIterator path = pos.path();
while (path.hasNext()) {
path.nextSegment(line);
g.drawLine(line.x1, line.y1, line.x2, line.y2);
}
int speed = (int) Math.round(pos.getSpeed());
g.drawString("Speed: " + speed, 260, 60);
}
private void updateTrainPosition() {
Random rand = new Random(System.currentTimeMillis());
MoveTrainPreMove moveTrain = new MoveTrainPreMove(0, principal);
Move m;
if (rand.nextInt(10) == 0) {
m = moveTrain.stopTrain(world);
} else {
m = moveTrain.generateMove(world);
}
MoveStatus ms = m.doMove(world, principal);
if (!ms.ok)
throw new IllegalStateException(ms.message);
ActivityIterator ai = world.getActivities(principal, 0);
while (ai.hasNext()) {
ai.nextActivity();
finishTime = ai.getFinishTime();
}
}
public TrainMotionExpt() {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
TrackMoveProducer producer = new TrackMoveProducer(me, world, mr);
Step[] trackPath = { EAST, SOUTH_EAST, SOUTH, SOUTH_WEST, WEST,
NORTH_WEST, NORTH, NORTH_EAST };
ImPoint from = new ImPoint(5, 5);
MoveStatus ms = producer.buildTrack(from, trackPath);
if (!ms.ok)
throw new IllegalStateException(ms.message);
TrainOrdersModel[] orders = {};
ImmutableSchedule is = new ImmutableSchedule(orders, -1, false);
AddTrainPreMove addTrain = new AddTrainPreMove(0, new ImInts(), from,
principal, is);
Move m = addTrain.generateMove(world);
ms = m.doMove(world, principal);
if (!ms.ok)
throw new IllegalStateException(ms.message);
startTime = System.currentTimeMillis();
}
public static void main(String[] args) {
System.setProperty("SHOWFPS", "true");
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.getContentPane().add(new TrainMotionExpt());
ScreenHandler screenHandler = new ScreenHandler(f,
ScreenHandler.WINDOWED_MODE);
screenHandler.apply();
GameLoop gameLoop = new GameLoop(screenHandler);
Thread t = new Thread(gameLoop);
t.start();
}
}

RunMe

Full name: experimental.RunMe

Documentation

/**
* Tests that ClientJFrame and ScreenHandler work together.
*
* @author Luke Lindsay
*/

Source Code

/**
* Tests that ClientJFrame and ScreenHandler work together.
*
* @author Luke Lindsay
*/
public class RunMe {
public static void main(String[] args) {
JFrame jFrame = new jfreerails.client.top.ClientJFrame(
new SimpleComponentFactoryImpl2());
// jFrame.show();
ScreenHandler screenHandler = new ScreenHandler(jFrame,
ScreenHandler.WINDOWED_MODE);
GameLoop gameLoop = new GameLoop(screenHandler);
Thread t = new Thread(gameLoop);
t.start();
}
}

Methods

GenerateTrainHighlights

Full name: experimental.GenerateTrainHighlights

Documentation

/**
* Generates image files that can be used to indicate that a train has focus or
* is selected. The image files are semi transparent and are intended to be
* rendered 'under' the images of the train's engine and wagons.
*
*
* @author Luke
*/

Source Code

/**
* Generates image files that can be used to indicate that a train has focus or
* is selected. The image files are semi transparent and are intended to be
* rendered 'under' the images of the train's engine and wagons.
*
*
* @author Luke
*/
public class GenerateTrainHighlights {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ImageManager imageManager = new ImageManagerImpl(
"/experimental/", "/experimental/");
UIDefaults lookAndFeelDefaults = UIManager.getLookAndFeelDefaults();
Color selection = (Color) lookAndFeelDefaults.get("List.selectionBackground");
selection = makeTransparent(selection, 128);
String filename = "selected_%s.png";
gen(imageManager, selection, filename);
Color focus = (Color) lookAndFeelDefaults.get("TabbedPane.focus");
focus = makeTransparent(focus, 128);
filename = "focused_%s.png";
gen(imageManager, focus, filename);
try {
imageManager.writeAllImages();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void gen(ImageManager imageManager, Color selection, String filename) {
for (Step step : Step.getList()) {
int tileSize = 30;
Image smallImage = imageManager.newBlankImage(tileSize, tileSize);
Graphics2D g2 = (Graphics2D) smallImage.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(3));
double arcRadius = 5;
g2.rotate(step.getDirection(), tileSize/2, tileSize/2);
RoundRectangle2D roundedRectangle = new RoundRectangle2D.Double(7, 3, 16, 26, arcRadius, arcRadius);
g2.setColor(selection);
g2.fill(roundedRectangle);
g2.dispose();
String name = String.format(filename, step.toAbrvString());
imageManager.setImage(name, smallImage);
}
}
static Color makeTransparent(Color before, int alpha){
return new Color(before.getRed(), before.getGreen(), before.getBlue(), alpha);
}
}

ConnectAllCities

Full name: experimental.ConnectAllCities

Documentation

/**
*
* @author Luke
*/

Source Code

/**
*
* @author Luke
*/
public class ConnectAllCities {
static class DistanceComparator implements Comparator<CityModel> {
final int targetX, targetY;
public DistanceComparator(int targetX, int targetY) {
this.targetX = targetX;
this.targetY = targetY;
}
int distSquared(CityModel a) {
int xDist = a.getCityX() - targetX;
int yDist = a.getCityY() - targetY;
return xDist * xDist + yDist * yDist;
}
@Override
public int compare(CityModel a, CityModel b) {
return distSquared(a) - distSquared(b);
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException, PathNotFoundException {
SavedGamesManager gamesManager = new SavedGamesManagerImpl();
String[] newMapNames = gamesManager.getNewMapNames();
World w = (World) gamesManager.newMap(newMapNames[0]);
System.out.println(w.getClass());
ServerGameModel gameModel = new ServerGameModelImpl();
String name = "Tester";
Player p = new Player(name, 0);
Move addPlayerMove = AddPlayerMove.generateMove(w, p);
MoveStatus ms = addPlayerMove.doMove(w, Player.AUTHORITATIVE);
w.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
w.setTime(new GameTime(0));
w.set(ITEM.GAME_SPEED, new GameSpeed(10));
w.set(ITEM.GAME_RULES, GameRules.DEFAULT_RULES);
Transaction t = new AddItemTransaction(Transaction.Category.BOND, 0, 1, new Money(50000000));
w.addTransaction(p.getPrincipal(), t);
List<CityModel> citiesUnconnected = new ArrayList<>();
List<CityModel> citiesConnected = new ArrayList<>();
int nCities = w.size(SKEY.CITIES);
System.out.format("There are %d cities.%n", nCities);
for (int i = 0; i < nCities; i++) {
citiesUnconnected.add((CityModel) w.get(SKEY.CITIES, i));
}
CityModel cityA = citiesUnconnected.remove(0);
citiesConnected.add(cityA);
DistanceComparator distanceComparator = new DistanceComparator(cityA.getCityX(), cityA.getCityY());
Collections.sort(citiesUnconnected, distanceComparator);
MapCustomizer mc = new MapCustomizer(w);
int n = citiesUnconnected.size();
for (int i = 0; i < n; i++) {
CityModel cityB = citiesUnconnected.remove(0);
System.out.format("build track to %s%n", cityB.getCityName());
distanceComparator = new DistanceComparator(cityB.getCityX(), cityB.getCityY());
Collections.sort(citiesConnected, distanceComparator);
ImPoint b = cityB.getLocation();
for (int j = 0; j < Math.min(3, citiesConnected.size()); j++) {
cityA = citiesConnected.get(j);
ImPoint a = cityA.getLocation();
mc.buildTrack(a, b);
try {
if (j == 0) {
if (i == 0) {
mc.buildStation(a);
}
mc.buildStation(b);
}
} catch (java.lang.IllegalStateException e) {
//sometimes it is not possible to build the
//stations, e.g. another one is too close.
break;
}
int stationA = mc.getStationId(a);
int stationB = mc.getStationId(b);
if (stationA >= 0 && stationB >= 0) {
//the stations exist.
mc.buildTrain(b, stationA, stationB);
}
}
System.out.format("There are %d stations%n", w.size(p.getPrincipal(), KEY.STATIONS));
citiesConnected.add(cityB);
}
System.out.println(ms);
String[] passwords = {"password"};
gameModel.setWorld(w, passwords);
gamesManager.saveGame(gameModel, "generated.sav");
}
}

Methods

JavaDocPlaceholder

Full name: jfreerails.JavaDocPlaceholder

Documentation

/**
* This class does nothing and is only here so that javadoc gets generated
* correctly.
*
* @author Luke
*
*/

Source Code

/**
* This class does nothing and is only here so that javadoc gets generated
* correctly.
*
* @author Luke
*
*/
public class JavaDocPlaceholder {
}

Methods

No methods found

AddActiveEntityMoveTest

Full name: jfreerails.move.AddActiveEntityMoveTest

Documentation

/**
* Tests the AddActiveEntityMove class to ensure it correctly handles
* serialization, non-repeatability, and failure on repeated moves.
*
* This test case verifies that an AddActiveEntityMove instance can be
* serialized and deserialized without issues, that it is not repeatable,
* and that attempting to move again after an initial move fails.
*
* @author John Doe
* @see AddActiveEntityMove
* @see WorldImplTest.TestActivity
*/

Source Code

public class AddActiveEntityMoveTest extends AbstractMoveTestCase {
@Override
public void testMove() {
FreerailsPrincipal p = getPrincipal();
Activity a = new WorldImplTest.TestActivity(50);
AddActiveEntityMove move = new AddActiveEntityMove(a, 0,
p);
assertSurvivesSerialisation(move);
assertOkButNotRepeatable(move);
AddActiveEntityMove move2 = new AddActiveEntityMove(a, 2,
p);
assertTryMoveFails(move2);
}
}

Methods

ListMove

Full name: jfreerails.move.ListMove

Documentation

/**
* This interface provides information about changes to the lists in the World
* database.
*
* @author rob?
*/

Source Code

/**
* This interface provides information about changes to the lists in the World
* database.
*
* @author rob?
*/
public interface ListMove extends Move {
/**
* @return the type of object which was changed
*/
KEY getKey();
/**
* @return the old item or null if not any.
*/
FreerailsSerializable getBefore();
/**
* @return the new item or null if not any.
*/
FreerailsSerializable getAfter();
/**
* @return the index of the item which changed.
*/
int getIndex();
FreerailsPrincipal getPrincipal();
}

NextActivityMoveTest

Full name: jfreerails.move.NextActivityMoveTest

Documentation

/**
* Test class for verifying the behavior of the {@link NextActivityMove} class.
* This class contains test cases to ensure that the move operation correctly handles
* serialization, undo/redo functionality, and activity stacking within a world.
*
* @author Your Name
* @see AbstractMoveTestCase
* @see NextActivityMove
* @see World
* @see FreerailsPrincipal
* @see Activity
*/

Source Code

public class NextActivityMoveTest extends AbstractMoveTestCase {
@Override
public void testMove() {
World w = getWorld();
FreerailsPrincipal principal = getPrincipal();
Activity act = new WorldImplTest.TestActivity(50);
w.addActiveEntity(principal, act);
Activity act2 = new WorldImplTest.TestActivity(60);
Move move = new NextActivityMove(act2, 0,
principal);
assertSurvivesSerialisation(move);
assertOkAndRepeatable(move);
}
public void testMove2() {
World w = getWorld();
FreerailsPrincipal principal = getPrincipal();
Activity act = new WorldImplTest.TestActivity(50);
w.addActiveEntity(principal, act);
Activity act2 = new WorldImplTest.TestActivity(60);
Move move = new NextActivityMove(act2, 0,
principal);
assertDoThenUndoLeavesWorldUnchanged(move);
}
public void testStackingOfActivities() {
World w = getWorld();
FreerailsPrincipal principal = getPrincipal();
Activity act = new WorldImplTest.TestActivity(50);
w.addActiveEntity(principal, act);
Activity act2 = new WorldImplTest.TestActivity(60);
Move move = new NextActivityMove(act2, 0,
principal);
assertDoMoveIsOk(move);
GameTime currentTime = new GameTime(0);
assertEquals(currentTime, w.currentTime());
ActivityIterator it = w.getActivities(principal, 0);
assertEquals(it.getActivity(), act);
assertEquals(it.getStartTime(), currentTime.getTicks(), 0.00001);
assertEquals(50d, it.getDuration(), 0.00001);
assertEquals(50d, it.getFinishTime(), 0.00001);
assertTrue(it.hasNext());
it.nextActivity();
assertEquals(it.getActivity(), act2);
assertEquals(50, it.getStartTime(), 0.00001);
assertEquals(60, it.getDuration(), 0.0001d);
assertEquals(110, it.getFinishTime(), 0.00001);
}
}

ChangeCargoBundleMoveTest

Full name: jfreerails.move.ChangeCargoBundleMoveTest

Documentation

/**
* JUnit test.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test.
*
* @author Luke
*
*/
public class ChangeCargoBundleMoveTest extends AbstractMoveTestCase {
@Override
public void testMove() {
MutableCargoBundle before;
MutableCargoBundle after;
before = new MutableCargoBundle();
after = new MutableCargoBundle();
before.setAmount(new CargoBatch(1, 2, 3, 4, 0), 5);
after.setAmount(new CargoBatch(1, 2, 3, 4, 0), 8);
Move m = new ChangeCargoBundleMove(before.toImmutableCargoBundle(),
after.toImmutableCargoBundle(), 0,
MapFixtureFactory.TEST_PRINCIPAL);
assertSurvivesSerialisation(m);
assertTryMoveFails(m);
assertTryUndoMoveFails(m);
getWorld().add(MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES,
before.toImmutableCargoBundle());
}
}

Methods

ChangeTrackPieceCompositeMoveTest

Full name: jfreerails.move.ChangeTrackPieceCompositeMoveTest

Documentation

/**
* JUnit test.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test.
*
* @author Luke
*
*/
public class ChangeTrackPieceCompositeMoveTest extends AbstractMoveTestCase {
final Step southeast = Step.SOUTH_EAST;
final Step east = Step.EAST;
final Step northeast = Step.NORTH_EAST;
final Step south = Step.SOUTH;
final Step west = Step.WEST;
TrackMoveTransactionsGenerator transactionsGenerator;
public ChangeTrackPieceCompositeMoveTest(java.lang.String testName) {
super(testName);
}
public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}
public static Test suite() {
TestSuite testSuite = new TestSuite(
ChangeTrackPieceCompositeMoveTest.class);
return testSuite;
}
@Override
protected void setUp() {
super.setHasSetupBeenCalled(true);
setWorld(new WorldImpl(10, 10));
getWorld().set(ITEM.GAME_RULES, GameRules.DEFAULT_RULES);
getWorld().addPlayer(MapFixtureFactory.TEST_PLAYER);
MapFixtureFactory.generateTrackRuleList(getWorld());
transactionsGenerator = new TrackMoveTransactionsGenerator(getWorld(),
MapFixtureFactory.TEST_PRINCIPAL);
}
public void testRemoveTrack() {
getWorld().set(ITEM.GAME_RULES, GameRules.NO_RESTRICTIONS);
TrackRule trackRule = (TrackRule) getWorld().get(SKEY.TRACK_RULES, 0);
assertBuildTrackSucceeds(new ImPoint(0, 5), east, trackRule);
assertBuildTrackSucceeds(new ImPoint(0, 6), east, trackRule);
assertBuildTrackSucceeds(new ImPoint(1, 6), east, trackRule);
assertBuildTrackSucceeds(new ImPoint(0, 7), east, trackRule);
assertBuildTrackSucceeds(new ImPoint(1, 7), east, trackRule);
assertBuildTrackSucceeds(new ImPoint(2, 7), east, trackRule);
// Remove only track piece built.
assertRemoveTrackSucceeds(new ImPoint(0, 5), east);
TrackConfiguration trackConfiguration = ((FreerailsTile) getWorld().getTile(0, 5))
.getTrackPiece().getTrackConfiguration();
TrackConfiguration expected = NullTrackPiece.getInstance().getTrackConfiguration();
assertEquals(expected,
trackConfiguration);
TrackConfiguration trackConfiguration2 = ((FreerailsTile) getWorld().getTile(1, 5))
.getTrackPiece().getTrackConfiguration();
assertEquals(expected,
trackConfiguration2);
}
/**
* All track except the first piece built should be connected to existing
* track.
*/
public void testMustConnect2ExistingTrack() {
TrackRule trackRule = (TrackRule) world.get(SKEY.TRACK_RULES, 0);
int numberOfTransactions = world
.getNumberOfTransactions(MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(0, numberOfTransactions);
boolean hasTrackBeenBuilt = ChangeTrackPieceCompositeMove
.hasAnyTrackBeenBuilt(world, MapFixtureFactory.TEST_PRINCIPAL);
assertFalse("No track has been built yet.", hasTrackBeenBuilt);
assertBuildTrackSucceeds(new ImPoint(0, 5), east, trackRule);
// Building the track should have added a transaction.
numberOfTransactions = world
.getNumberOfTransactions(MapFixtureFactory.TEST_PRINCIPAL);
assertTrue(0 < numberOfTransactions);
hasTrackBeenBuilt = ChangeTrackPieceCompositeMove.hasAnyTrackBeenBuilt(
world, MapFixtureFactory.TEST_PRINCIPAL);
assertTrue("One track piece has been built.", hasTrackBeenBuilt);
assertBuildTrackSucceeds(new ImPoint(1, 5), east, trackRule);
assertBuildTrackFails(new ImPoint(4, 8), east, trackRule);
}
public void testCannotConnect2OtherRRsTrack() {
assertFalse(ChangeTrackPieceMove.canConnect2OtherRRsTrack(world));
final int TRACK_RULE_ID = 0;
TrackRule trackRule = (TrackRule) getWorld().get(SKEY.TRACK_RULES,
TRACK_RULE_ID);
assertBuildTrackSucceeds(new ImPoint(0, 6), east, trackRule);
// Now change the owner of the track piece at (1, 6);
int anotherPlayer = 999;
FreerailsTile oldTile = (FreerailsTile) world.getTile(1, 6);
TrackPiece tp = oldTile.getTrackPiece();
TrackPiece newTrackPiece = new TrackPieceImpl(tp
.getTrackConfiguration(), tp.getTrackRule(), anotherPlayer,
TRACK_RULE_ID);
FreerailsTile newTile = FreerailsTile.getInstance(oldTile
.getTerrainTypeID(), newTrackPiece);
world.setTile(1, 6, newTile);
assertBuildTrackFails(new ImPoint(1, 6), east, trackRule);
world.setTile(1, 6, oldTile);
assertBuildTrackSucceeds(new ImPoint(1, 6), east, trackRule);
}
public void testBuildTrack() {
ImPoint pointA = new ImPoint(0, 0);
ImPoint pointB = new ImPoint(1, 1);
ImPoint pointC = new ImPoint(1, 0);
TrackRule trackRule = (TrackRule) getWorld().get(SKEY.TRACK_RULES, 0);
// First track piece built
assertBuildTrackSucceeds(pointA, southeast, trackRule);
// Track connected from one existing track piece
assertBuildTrackSucceeds(pointB, northeast, trackRule);
// Track connected to one existing track piece
// This is not going through for some reason, not sure why.
// assertBuildTrackSucceeds(pointC, west, trackRule);
// Track connecting two existing track pieces.
assertBuildTrackSucceeds(pointA, east, trackRule);
// Track off map.. should fail.
assertBuildTrackFails(pointA, northeast, trackRule);
// Track already there.
assertBuildTrackFails(pointA, southeast, trackRule);
// Illegal config. connecting from one existing track piece
assertBuildTrackFails(pointA, south, trackRule);
// Illegal config. connecting to one existing track piece
assertBuildTrackFails(new ImPoint(0, 1), northeast, trackRule);
// Illegal config. connecting between two existing track pieces
assertBuildTrackFails(pointC, south, trackRule);
// Not allowed on this terrain type, from existing track.
assertBuildTrackFails(new ImPoint(2, 0), northeast,
(TrackRule) getWorld().get(SKEY.TRACK_RULES, 1));
}
private void assertBuildTrackFails(ImPoint p, Step v, TrackRule rule) {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(p, v, rule, rule, getWorld(),
MapFixtureFactory.TEST_PRINCIPAL);
MoveStatus status = move.doMove(getWorld(), Player.AUTHORITATIVE);
assertEquals(false, status.isOk());
}
private void assertBuildTrackSucceeds(ImPoint p, Step v, TrackRule rule) {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(p, v, rule, rule, getWorld(),
MapFixtureFactory.TEST_PRINCIPAL);
Move moveAndTransaction = transactionsGenerator.addTransactions(move);
MoveStatus status = moveAndTransaction.doMove(getWorld(),
Player.AUTHORITATIVE);
assertEquals(true, status.isOk());
}
private void assertRemoveTrackSucceeds(ImPoint p, Step v) {
try {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateRemoveTrackMove(p, v, getWorld(),
MapFixtureFactory.TEST_PRINCIPAL);
MoveStatus status = move.doMove(getWorld(), Player.AUTHORITATIVE);
assertEquals(true, status.isOk());
} catch (Exception e) {
fail();
}
}
@Override
public void testMove() {
ImPoint pointA = new ImPoint(0, 0);
TrackRule trackRule = (TrackRule) getWorld().get(SKEY.TRACK_RULES, 0);
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(pointA, southeast, trackRule,
trackRule, getWorld(), MapFixtureFactory.TEST_PRINCIPAL);
assertSurvivesSerialisation(move);
assertOkButNotRepeatable(move);
setUp();
assertDoThenUndoLeavesWorldUnchanged(move);
}
}

AddPlayerMoveTest

Full name: jfreerails.move.AddPlayerMoveTest

Documentation

/**
* Test class for verifying the functionality of the {@link AddPlayerMove} class.
* This class ensures that the AddPlayerMove correctly handles serialization,
* undo operations, and non-repeatability constraints.
*
* @author John Doe
* @since 1.0
* @see AddPlayerMove
* @see AbstractMoveTestCase
* @see Utils
*/

Source Code

public class AddPlayerMoveTest extends AbstractMoveTestCase {
@Override
public void testMove() {
Player newPlayer = new Player("New Player");
assertTrue("Check reflexivity of Player.equals(.)", Utils
.equalsBySerialization(newPlayer, newPlayer));
AddPlayerMove move = AddPlayerMove.generateMove(getWorld(), newPlayer);
assertSurvivesSerialisation(move);
assertDoThenUndoLeavesWorldUnchanged(move);
}
public void testMove2() {
Player newPlayer = new Player("New Player");
AddPlayerMove move = AddPlayerMove.generateMove(getWorld(), newPlayer);
assertOkButNotRepeatable(move);
}
}

TrackMoveTransactionsGeneratorTest

Full name: jfreerails.move.TrackMoveTransactionsGeneratorTest

Documentation

/**
* JUnit test case for TrackMoveTransactionsGenerator.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* JUnit test case for TrackMoveTransactionsGenerator.
*
* @author Luke Lindsay
*
*/
public class TrackMoveTransactionsGeneratorTest extends TestCase {
private World world;
private TrackMoveTransactionsGenerator transactionGenerator;
private Player player;
@Override
protected void setUp() throws Exception {
world = new WorldImpl(20, 20);
MapFixtureFactory.generateTrackRuleList(world);
player = new Player("test player", 0);
world.addPlayer(player);
transactionGenerator = new TrackMoveTransactionsGenerator(world, player
.getPrincipal());
}
public void testAddTrackMove() {
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
TrackConfiguration newConfig;
TrackMove move;
// Try building the simplest piece of track.
newConfig = TrackConfiguration.getFlatInstance("000010000");
oldTrackPiece = ((FreerailsTile) world.getTile(0, 0)).getTrackPiece();
TrackRule r = (TrackRule) world.get(SKEY.TRACK_RULES, 0);
int owner = ChangeTrackPieceCompositeMove.getOwner(
MapFixtureFactory.TEST_PRINCIPAL, world);
newTrackPiece = new TrackPieceImpl(newConfig, r, owner, 0);
move = new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece,
new ImPoint(0, 0));
Move m = transactionGenerator.addTransactions(move);
assertNotNull(m);
}
}

NextActivityMove

Full name: jfreerails.move.NextActivityMove

Documentation

/**
* Represents a move to advance to the next activity in a sequence for a given principal.
* This class encapsulates the logic for performing and undoing the move, ensuring
* validity through the MoveStatus enum. It is responsible for managing activity transitions
* within a world state.
*
* @author John Doe
* @see Move
* @see Activity
* @see FreerailsPrincipal
* @see World
*/

Source Code

public class NextActivityMove implements Move {
private static final long serialVersionUID = -1783556069173689661L;
private final Activity activity;
private final FreerailsPrincipal principal;
private final int index;
public NextActivityMove(Activity activity, int index,
FreerailsPrincipal principal) {
this.activity = activity;
this.index = index;
this.principal = principal;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof NextActivityMove))
return false;
final NextActivityMove nextActivityMove = (NextActivityMove) o;
if (index != nextActivityMove.index)
return false;
if (!activity.equals(nextActivityMove.activity))
return false;
if (!principal.equals(nextActivityMove.principal))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = activity.hashCode();
result = 29 * result + principal.hashCode();
result = 29 * result + index;
return result;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
// Check that active entity exists.
if (w.size(principal) <= index)
return MoveStatus.moveFailed("Index out of range. "+w.size(principal)+"<= "+index);
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
ActivityIterator ai = w.getActivities(principal, index);
ai.gotoLastActivity();
Activity act = ai.getActivity();
if (act.equals(activity))
return MoveStatus.MOVE_OK;
return MoveStatus.moveFailed("Expected " + activity + " but found "
+ act);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.ok)
w.add(principal, index, activity);
return ms;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.ok)
w.removeLastActivity(principal, index);
return ms;
}
}

MapDiffMoveTest

Full name: jfreerails.move.MapDiffMoveTest

Documentation

/**
* JUnit test for MapDiffMove.
*
* @author Luke
*/

Source Code

/**
* JUnit test for MapDiffMove.
*
* @author Luke
*/
public class MapDiffMoveTest extends AbstractMoveTestCase {
@Override
public void testMove() {
World world2 = this.getWorld();
WorldDiffs worldDiff = new WorldDiffs(world2);
FreerailsTile tile = (FreerailsTile) world2.getTile(2, 2);
assertNotNull(tile);
assertEquals(tile, worldDiff.getTile(2, 2));
FreerailsTile newTile = FreerailsTile.getInstance(999);
worldDiff.setTile(3, 5, newTile);
assertEquals(newTile, worldDiff.getTile(3, 5));
Move m = new WorldDiffMove(world2, worldDiff, WorldDiffMove.Cause.Other);
this.assertDoMoveIsOk(m);
this.assertUndoMoveIsOk(m);
this.assertDoThenUndoLeavesWorldUnchanged(m);
this.assertSurvivesSerialisation(m);
}
}

Methods

TrackMoveTransactionsGenerator

Full name: jfreerails.move.TrackMoveTransactionsGenerator

Documentation

/**
* This class calculates the cost of a series of track moves. The motivation for
* separating this code from the code that generates track moves is that the
* transactions will be generated by the server whereas the track moves will be
* generated by a client.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* This class calculates the cost of a series of track moves. The motivation for
* separating this code from the code that generates track moves is that the
* transactions will be generated by the server whereas the track moves will be
* generated by a client.
*
* @author Luke Lindsay
*
*/
public class TrackMoveTransactionsGenerator {
/** Number of each of the track types added. */
private int[] trackAdded;
private long fixedCostsStations = 0;
private long fixedCostsBridges = 0;
/** Number of each of the track types removed. */
private int[] trackRemoved;
private final FreerailsPrincipal principal;
/*
* Note, trackAdded and trackRemoved cannot be combined, since it may cost
* more to added a unit of track than is refunded when you removed it.
*/
private final ArrayList<Transaction> transactions = new ArrayList<Transaction>();
private final ReadOnlyWorld w;
/**
* @param p
* the Principal on behalf of which this object generates
* transactions for
*/
public TrackMoveTransactionsGenerator(ReadOnlyWorld world,
FreerailsPrincipal p) {
w = world;
principal = p;
}
public CompositeMove addTransactions(Move move) {
int numberOfTrackTypes = w.size(SKEY.TRACK_RULES);
trackAdded = new int[numberOfTrackTypes];
trackRemoved = new int[numberOfTrackTypes];
fixedCostsStations = 0;
fixedCostsBridges = 0;
unpackMove(move);
generateTransactions();
int numberOfMoves = 1 + transactions.size();
Move[] moves = new Move[numberOfMoves];
moves[0] = move;
for (int i = 0; i < transactions.size(); i++) {
Transaction t = transactions.get(i);
moves[i + 1] = new AddTransactionMove(principal, t, true);
}
return new CompositeMove(moves);
}
private void unpackMove(Move move) {
if (move instanceof ChangeTrackPieceMove) {
ChangeTrackPieceMove tm = (ChangeTrackPieceMove) move;
processMove(tm);
} else if (move instanceof CompositeMove) {
CompositeMove cm = (CompositeMove) move;
cm.getMoves();
ImList<Move> moves = cm.getMoves();
for (int i = 0; i < moves.size(); i++) {
unpackMove(moves.get(i));
}
}
}
private void processMove(ChangeTrackPieceMove move) {
TrackPiece newTrackPiece = move.getNewTrackPiece();
TrackRule newTrackRule = newTrackPiece.getTrackRule();
final int ruleAfter = newTrackPiece.getTrackTypeID();
TrackPiece oldTrackPiece = move.getOldTrackPiece();
final int ruleBefore = oldTrackPiece.getTrackTypeID();
final int oldLength = oldTrackPiece.getTrackConfiguration().getLength();
final int newLength = newTrackPiece.getTrackConfiguration().getLength();
if (ruleAfter != ruleBefore) {
TrackRule.TrackCategories category = newTrackRule.getCategory();
switch (category) {
case station: {
fixedCostsStations -= newTrackRule.getFixedCost().getAmount();
break;
}
case bridge: {
fixedCostsBridges -= newTrackRule.getFixedCost().getAmount();
break;
}
default: {
// Do nothing.
}
}
}
if (ruleAfter == ruleBefore) {
if (oldLength < newLength) {
trackAdded[ruleAfter] += (newLength - oldLength);
} else if (oldLength > newLength) {
trackRemoved[ruleAfter] += (oldLength - newLength);
}
return;
}
if (ruleAfter != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
trackAdded[ruleAfter] += newLength;
}
if (ruleBefore != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
trackRemoved[ruleBefore] += oldLength;
}
}
private void generateTransactions() {
transactions.clear();
// For each track type, generate a transaction if any pieces of the type
// have been added or removed.
for (int i = 0; i < trackAdded.length; i++) {
int numberAdded = trackAdded[i];
if (0 != numberAdded) {
TrackRule rule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
Money m = rule.getPrice();
Money total = new Money(-m.getAmount() * numberAdded
/ TrackConfiguration.LENGTH_OF_STRAIGHT_TRACK_PIECE);
Transaction t = new AddItemTransaction(TRACK, i, numberAdded,
total);
transactions.add(t);
}
int numberRemoved = trackRemoved[i];
if (0 != numberRemoved) {
TrackRule rule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
Money m = rule.getPrice();
Money total = new Money((m.getAmount() * numberRemoved)
/ TrackConfiguration.LENGTH_OF_STRAIGHT_TRACK_PIECE);
// You only get half the money back.
total = new Money(total.getAmount() / 2);
Transaction t = new AddItemTransaction(TRACK, i,
-numberRemoved, total);
transactions.add(t);
}
}
if (0 != fixedCostsStations) {
Transaction t = new AddItemTransaction(STATIONS, -1, -1, new Money(
fixedCostsStations));
transactions.add(t);
}
if (0 != fixedCostsBridges) {
Transaction t = new AddItemTransaction(BRIDGES, -1, -1, new Money(
fixedCostsBridges));
transactions.add(t);
}
}
}

CompositeMoveTest

Full name: jfreerails.move.CompositeMoveTest

Documentation

/**
* JUnit test.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test.
*
* @author Luke
*
*/
public class CompositeMoveTest extends AbstractMoveTestCase {
final StationModel station1 = new StationModel(1, 1, "station1", 10, 0);
final StationModel station2 = new StationModel(2, 3, "station2", 10, 0);
final StationModel station3 = new StationModel(3, 3, "station3", 10, 0);
final StationModel station4 = new StationModel(4, 4, "station4", 10, 0);
@Override
public void testMove() {
Move[] moves = new Move[4];
moves[0] = new AddItemToListMove(KEY.STATIONS, 0, station1,
MapFixtureFactory.TEST_PRINCIPAL);
moves[1] = new AddItemToListMove(KEY.STATIONS, 1, station2,
MapFixtureFactory.TEST_PRINCIPAL);
moves[2] = new AddItemToListMove(KEY.STATIONS, 2, station3,
MapFixtureFactory.TEST_PRINCIPAL);
moves[3] = new AddItemToListMove(KEY.STATIONS, 3, station4,
MapFixtureFactory.TEST_PRINCIPAL);
Move compositeMove = new CompositeMove(moves);
assertSurvivesSerialisation(compositeMove);
assertTryMoveIsOk(compositeMove);
assertEquals("The stations should not have been add yet.", 0,
getWorld().size(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS));
assertDoMoveIsOk(compositeMove);
assertEquals("The stations should have been add now.", 4, getWorld()
.size(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS));
assertTryUndoMoveIsOk(compositeMove);
assertUndoMoveIsOk(compositeMove);
assertOkButNotRepeatable(compositeMove);
}
}

Methods

TimeTickMove

Full name: jfreerails.move.TimeTickMove

Documentation

/**
*
* Changes the time item on the world object.
*
* @author rob
*/

Source Code

/**
*
* Changes the time item on the world object.
*
* @author rob
*/
public class TimeTickMove implements Move {
private static final long serialVersionUID = 3257290240212153393L;
private final GameTime oldTime;
private final GameTime newTime;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TimeTickMove))
return false;
final TimeTickMove timeTickMove = (TimeTickMove) o;
if (!newTime.equals(timeTickMove.newTime))
return false;
if (!oldTime.equals(timeTickMove.oldTime))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = oldTime.hashCode();
result = 29 * result + newTime.hashCode();
return result;
}
public static TimeTickMove getMove(ReadOnlyWorld w) {
GameTime oldTime = w.currentTime();
GameTime newTime = new GameTime(oldTime.getTicks() + 1);
return new TimeTickMove(oldTime, newTime);
}
public TimeTickMove(GameTime oldTime, GameTime newTime) {
this.oldTime = oldTime;
this.newTime = newTime;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.currentTime().equals(oldTime)) {
return MoveStatus.MOVE_OK;
}
String string = "oldTime = " + oldTime.getTicks() + " <=> "
+ "currentTime " + (w.currentTime()).getTicks();
return MoveStatus.moveFailed(string);
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
GameTime time = w.currentTime();
if (time.equals(newTime)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + newTime + ", found " + time);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryDoMove(w, p);
if (status.ok) {
w.setTime(newTime);
}
return status;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryUndoMove(w, p);
if (status.isOk()) {
w.setTime(oldTime);
}
return status;
}
@Override
public String toString() {
return "TimeTickMove: " + oldTime + "=>" + newTime;
}
}

ChangeTrackPieceMoveTest

Full name: jfreerails.move.ChangeTrackPieceMoveTest

Documentation

/**
* JUnit test.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test.
*
* @author Luke
*
*/
public class ChangeTrackPieceMoveTest extends AbstractMoveTestCase {
public ChangeTrackPieceMoveTest(String testName) {
super(testName);
}
public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}
public static junit.framework.Test suite() {
junit.framework.TestSuite testSuite = new junit.framework.TestSuite(
ChangeTrackPieceMoveTest.class);
return testSuite;
}
@Override
protected void setUp() {
setHasSetupBeenCalled(true);
setWorld(new WorldImpl(20, 20));
getWorld().set(ITEM.GAME_RULES, GameRules.NO_RESTRICTIONS);
MapFixtureFactory.generateTrackRuleList(getWorld());
}
public void testTryDoMove() {
setUp();
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
TrackConfiguration newConfig;
TrackMove move;
MoveStatus moveStatus;
// Try building the simplest piece of track.
newConfig = TrackConfiguration.getFlatInstance("000010000");
oldTrackPiece = ((FreerailsTile) getWorld().getTile(0, 0)).getTrackPiece();
final int trackRuleID = 0;
final TrackRule r = (TrackRule) getWorld().get(SKEY.TRACK_RULES,
trackRuleID);
newTrackPiece = new TrackPieceImpl(newConfig, r, 0, trackRuleID);
move = new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece,
new ImPoint(0, 0));
moveStatus = move.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(moveStatus);
assertEquals(true, moveStatus.isOk());
// As above but with newTrackPiece and oldTrackPiece in the wrong order,
// should fail.
move = new ChangeTrackPieceMove(newTrackPiece, oldTrackPiece,
new ImPoint(0, 0));
moveStatus = move.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(moveStatus);
assertEquals(false, moveStatus.isOk());
// Try a move that does nothing, i.e. oldTrackPiece==newTrackPiece,
// should fail.
move = new ChangeTrackPieceMove(oldTrackPiece, oldTrackPiece,
new ImPoint(0, 0));
moveStatus = move.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(moveStatus);
assertEquals(false, moveStatus.isOk());
// Try buildingtrack outside the map.
move = new ChangeTrackPieceMove(newTrackPiece, oldTrackPiece,
new ImPoint(100, 0));
moveStatus = move.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(moveStatus);
assertEquals(false, moveStatus.isOk());
// Try building an illegal track configuration.
newConfig = TrackConfiguration.getFlatInstance("000011111");
newTrackPiece = new TrackPieceImpl(newConfig, r, 0, trackRuleID);
move = new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece,
new ImPoint(0, 0));
moveStatus = move.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertEquals(false, moveStatus.isOk());
}
public void testTryUndoMove() {
setUp();
}
public void testDoMove() {
setUp();
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
TrackConfiguration newConfig;
// Try building the simplest piece of track.
newConfig = TrackConfiguration.getFlatInstance("000010000");
oldTrackPiece = ((FreerailsTile) getWorld().getTile(0, 0)).getTrackPiece();
TrackRule r = (TrackRule) getWorld().get(SKEY.TRACK_RULES, 0);
newTrackPiece = new TrackPieceImpl(newConfig, r, 0, 0);
assertMoveDoMoveIsOk(oldTrackPiece, newTrackPiece);
}
protected void assertMoveDoMoveIsOk(TrackPiece oldTrackPiece,
TrackPiece newTrackPiece) {
TrackMove move;
MoveStatus moveStatus;
move = new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece,
new ImPoint(0, 0));
moveStatus = move.doMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(moveStatus);
assertEquals(true, moveStatus.isOk());
TrackConfiguration actual = ((FreerailsTile)getWorld().getTile(0, 0)).getTrackPiece().getTrackConfiguration();
assertEquals(newTrackPiece.getTrackConfiguration(),
actual);
}
@Override
public void testMove() {
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
TrackConfiguration newConfig;
newConfig = TrackConfiguration.getFlatInstance("000010000");
oldTrackPiece = ((FreerailsTile) getWorld().getTile(0, 0)).getTrackPiece();
TrackRule r = (TrackRule) getWorld().get(SKEY.TRACK_RULES, 0);
newTrackPiece = new TrackPieceImpl(newConfig, r, 0, 0);
Move move = new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece,
new ImPoint(0, 0));
assertSurvivesSerialisation(move);
assertOkButNotRepeatable(move);
}
}

WorldDiffMove

Full name: jfreerails.move.WorldDiffMove

Documentation

/**
* A move that makes a number of changes to the map and to the lists.
*
* WARNING: This class currently only handles the most common cases. A
* UnsupportedOperationException is thrown if an appropriate move
* cannot be generated.
*
*
* @author Luke
*/

Source Code

/**
* A move that makes a number of changes to the map and to the lists.
*
* WARNING: This class currently only handles the most common cases. A
* UnsupportedOperationException is thrown if an appropriate move
* cannot be generated.
*
*
* @author Luke
*/
public class WorldDiffMove implements Move, MapUpdateMove {
public enum Cause{TrainArrives, Other, YearEnd};
private final Cause cause;
private static final Logger logger = Logger.getLogger(WorldDiffMove.class
.getName());
static class MapDiff implements FreerailsSerializable {
private static final long serialVersionUID = -5935670372745313360L;
final FreerailsSerializable before, after;
final int x, y;
MapDiff(FreerailsSerializable before, FreerailsSerializable after,
ImPoint p) {
this.after = after;
this.before = before;
this.x = p.x;
this.y = p.y;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof MapDiff))
return false;
final MapDiff diff = (MapDiff) o;
if (x != diff.x)
return false;
if (y != diff.y)
return false;
if (!after.equals(diff.after))
return false;
if (!before.equals(diff.before))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = x;
result = 29 * result + y;
result = 29 * result + before.hashCode();
result = 29 * result + after.hashCode();
return result;
}
}
private static final long serialVersionUID = 3905245632406239544L;
public static WorldDiffMove generate(WorldDiffs diffs, Cause cause) {
return new WorldDiffMove(diffs.getUnderlying(), diffs, cause);
}
private final ImList<MapDiff> diffs;
private final CompositeMove listChanges;
private final int x, y, w, h;
public WorldDiffMove(ReadOnlyWorld world, WorldDiffs worldDiffs, Cause cause) throws UnsupportedOperationException {
this.cause = cause;
Iterator<ImPoint> mit = worldDiffs.getMapDiffs();
ArrayList<MapDiff> diffsArrayList = new ArrayList<MapDiff>();
while (mit.hasNext()) {
ImPoint p = mit.next();
FreerailsSerializable oldTile = world.getTile(p.x, p.y);
FreerailsSerializable newTile = worldDiffs.getTile(p.x, p.y);
diffsArrayList.add(new MapDiff(oldTile, newTile, p));
}
diffs = new ImList<MapDiff>(diffsArrayList);
x = 0;
y = 0;
w = world.getMapWidth();
h = world.getMapHeight();
List<Move> tempList = new ArrayList<Move>();
Iterator<ListKey> lit = worldDiffs.getListDiffs();
while (lit.hasNext()) {
ListKey lkey = lit.next();
WorldDiffs.LISTID listId = (LISTID) lkey.getListID();
switch (listId) {
case LISTS: {
int playerId = lkey.getIndex()[0];
FreerailsPrincipal fp = worldDiffs.getPlayer(playerId)
.getPrincipal();
KEY k = KEY.getKey(lkey.getIndex()[1]);
if (lkey.getType() == Element) {
Move m;
int elementId = lkey.getIndex()[2];
// Are we changing an element?
if (elementId < world.size(fp, k)) {
FreerailsSerializable before = world.get(fp, k,
elementId);
FreerailsSerializable after = worldDiffs.get(fp, k,
elementId);
m = new ChangeItemInListMove(k, elementId, before,
after, fp);
} else {
FreerailsSerializable element = worldDiffs.get(fp, k,
elementId);
m = new AddItemToListMove(k, elementId, element, fp);
}
tempList.add(m);
} else {
assert (lkey.getType() == EndPoint);
Integer newSize = (Integer) worldDiffs.getDiff(lkey);
int oldSize = world.size(fp, k);
if (newSize < oldSize) {
throw new UnsupportedOperationException();
}
}
break;
}
case CURRENT_BALANCE:
// Do nothing. The transaction moves should take care of changing
// the values of current balance.
break;
case BANK_ACCOUNTS: {
int playerId = lkey.getIndex()[0];
FreerailsPrincipal fp = worldDiffs.getPlayer(playerId)
.getPrincipal();
if (lkey.getType() == Element) {
Move m;
int elementId = lkey.getIndex()[1];
// Are we changing an element?
if (elementId < world.getNumberOfTransactions(fp)) {
throw new UnsupportedOperationException();
}
Transaction t = worldDiffs.getTransaction(fp, elementId);
m = new AddTransactionMove(fp, t );
tempList.add(m);
} else {
assert (lkey.getType() == EndPoint);
Integer newSize = (Integer) worldDiffs.getDiff(lkey);
int oldSize = world.getNumberOfTransactions(fp);
if (newSize < oldSize) {
throw new UnsupportedOperationException();
}
}
break;
}
case ACTIVITY_LISTS:{
int playerId = lkey.getIndex()[0];
FreerailsPrincipal fp = worldDiffs.getPlayer(playerId)
.getPrincipal();
Object o = worldDiffs.getDiff(lkey);
logger.fine(lkey.toString() + " --> "+ o.toString());
switch (lkey.getIndex().length){
case 1:{
assert (lkey.getType() == EndPoint);
//Do nothing. Adding the activities will increase the
//size of the list.
break;
}
case 2:
assert (lkey.getType() == EndPoint);
//Do nothing. Adding the activities will increase the
//size of the list.
break;
case 3:{
Move m;
//Do we need to add a new active entity?
int entityId = lkey.getIndex()[1];
ActivityAndTime aat = (ActivityAndTime) worldDiffs.getDiff(lkey);
Activity act = aat.act;
int activityID = lkey.getIndex()[2];
if(entityId >= world.getNumberOfActiveEntities(fp) && 0 == activityID){
logger.fine("AddActiveEntityMove: "+act+" entityId="+entityId);
m = new AddActiveEntityMove(act, entityId, fp );
}else{
logger.fine("NextActivityMove: "+act+" entityId="+entityId);
m = new NextActivityMove(act,entityId, fp);
}
tempList.add(m);
break;
}default:
throw new UnsupportedOperationException(listId.toString());
}
break;
}
default:
throw new UnsupportedOperationException(listId.toString());
}
}
listChanges = new CompositeMove(tempList);
}
private void doMove(World world, boolean undo) {
for (int i = 0; i < diffs.size(); i++) {
MapDiff diff = diffs.get(i);
FreerailsSerializable tile = undo ? diff.before : diff.after;
world.setTile(diff.x, diff.y, tile);
}
}
public MoveStatus doMove(World world, FreerailsPrincipal p) {
MoveStatus ms = tryMapChanges(world, false);
if (!ms.ok)
return ms;
ms = listChanges.doMove(world, p);
if (ms.isOk()) {
doMove(world, false);
}
return ms;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof WorldDiffMove))
return false;
final WorldDiffMove mapDiffMove = (WorldDiffMove) o;
if (h != mapDiffMove.h)
return false;
if (w != mapDiffMove.w)
return false;
if (x != mapDiffMove.x)
return false;
if (y != mapDiffMove.y)
return false;
if (!diffs.equals(mapDiffMove.diffs))
return false;
return true;
}
public Rectangle getUpdatedTiles() {
return new Rectangle(x, y, w, h);
}
@Override
public int hashCode() {
int result;
result = diffs.hashCode();
result = 29 * result + x;
result = 29 * result + y;
result = 29 * result + w;
result = 29 * result + h;
return result;
}
public MoveStatus tryDoMove(World world, FreerailsPrincipal p) {
MoveStatus ms = tryMapChanges(world, false);
if (!ms.ok)
return ms;
return ms = listChanges.tryDoMove(world, p);
}
private MoveStatus tryMapChanges(World world, boolean undo) {
for (int i = 0; i < diffs.size(); i++) {
MapDiff diff = diffs.get(i);
FreerailsSerializable actual = world.getTile(diff.x, diff.y);
FreerailsSerializable expected = undo ? diff.after : diff.before;
if (!actual.equals(expected)) {
return MoveStatus.moveFailed("expected =" + expected
+ ", actual = " + actual);
}
}
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World world, FreerailsPrincipal p) {
MoveStatus ms = tryMapChanges(world, true);
if (!ms.ok)
return ms;
return ms = listChanges.tryUndoMove(world, p);
}
public int listDiffs() {
return listChanges.size();
}
public MoveStatus undoMove(World world, FreerailsPrincipal p) {
MoveStatus ms = tryMapChanges(world, true);
if (!ms.ok)
return ms;
ms = listChanges.undoMove(world, p);
if (ms.isOk()) {
doMove(world, true);
}
return ms;
}
public Cause getCause() {
return cause;
}
public CompositeMove getListChanges() {
return listChanges;
}
}

RemoveCargoBundleMoveTest

Full name: jfreerails.move.RemoveCargoBundleMoveTest

Documentation

/**
* JUnit test.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test.
*
* @author Luke
*
*/
public class RemoveCargoBundleMoveTest extends AbstractMoveTestCase {
@Override
public void testMove() {
MutableCargoBundle bundleA;
MutableCargoBundle bundleB;
bundleA = new MutableCargoBundle();
bundleB = new MutableCargoBundle();
bundleA.setAmount(new CargoBatch(1, 2, 3, 4, 0), 5);
bundleB.setAmount(new CargoBatch(1, 2, 3, 4, 0), 5);
assertEquals(bundleA, bundleB);
Move m = new RemoveCargoBundleMove(0, bundleB.toImmutableCargoBundle(),
MapFixtureFactory.TEST_PRINCIPAL);
assertSurvivesSerialisation(m);
assertTryMoveFails(m);
assertTryUndoMoveFails(m);
getWorld().add(MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES,
bundleA.toImmutableCargoBundle());
assertTryMoveIsOk(m);
assertOkButNotRepeatable(m);
}
}

Methods

Move

Full name: jfreerails.move.Move

Documentation

/**
* All moves should implement this interface and obey the contract described
* below.
* <p>
* (1) They should be immutable.
* </P>
* <p>
* (2) They should override <code>Object.equals()</code> to test for logical
* equality.
* </P>
* <p>
* (3) They should store 'before' and 'after' values for all properties of the
* world object that they change.
* <p>
* (4) The changes they encapsulate should be stored in an address space
* independent way, so that a move generated on a client can be serialised, sent
* over a network, and then deserialized and executed on a server. To achieve
* this, they should refer to items in the game world via either their
* coordinates, e.g. tile 10,50, or their position in a list, e.g. train #4.
* </p>
* <p>
* (5) They should be undoable. To achieve this, they need to store the
* information necessary to undo the change. E.g. a change-terrain-type move
* might store the tile coordinates, the terrain type before the change and the
* terrain type after the change.
* </p>
* <p>
* (6) The tryDoMove and tryUndoMove methods should test whether the move is
* valid but leave the gameworld unchanged
* </p>
*
* @see MoveStatus
* @see jfreerails.world.top.World
* @see jfreerails.controller.PreMove
* @author lindsal
*/

Source Code

/**
* All moves should implement this interface and obey the contract described
* below.
* <p>
* (1) They should be immutable.
* </P>
* <p>
* (2) They should override <code>Object.equals()</code> to test for logical
* equality.
* </P>
* <p>
* (3) They should store 'before' and 'after' values for all properties of the
* world object that they change.
* <p>
* (4) The changes they encapsulate should be stored in an address space
* independent way, so that a move generated on a client can be serialised, sent
* over a network, and then deserialized and executed on a server. To achieve
* this, they should refer to items in the game world via either their
* coordinates, e.g. tile 10,50, or their position in a list, e.g. train #4.
* </p>
* <p>
* (5) They should be undoable. To achieve this, they need to store the
* information necessary to undo the change. E.g. a change-terrain-type move
* might store the tile coordinates, the terrain type before the change and the
* terrain type after the change.
* </p>
* <p>
* (6) The tryDoMove and tryUndoMove methods should test whether the move is
* valid but leave the gameworld unchanged
* </p>
*
* @see MoveStatus
* @see jfreerails.world.top.World
* @see jfreerails.controller.PreMove
* @author lindsal
*/
public interface Move extends FreerailsSerializable {
/**
* Tests whether this Move can be executed on the specified world object,
* this method should leave the world object unchanged.
*/
MoveStatus tryDoMove(World w, FreerailsPrincipal p);
/**
* Tests whether this Move can be undone on the specified world object, this
* method should leave the world object unchanged.
*/
MoveStatus tryUndoMove(World w, FreerailsPrincipal p);
/**
* Executes this move on the specified world object.
*/
MoveStatus doMove(World w, FreerailsPrincipal p);
/**
* If <code>doMove</code> has just been executed on the specified world
* object, calling this method changes the state of the world object back to
* how it was before <code>doMove</code> was called.
*/
MoveStatus undoMove(World w, FreerailsPrincipal p);
}

ChangeTileMoveTest

Full name: jfreerails.move.ChangeTileMoveTest

Documentation

/**
* Tests the functionality of the ChangeTileMove class, ensuring it correctly modifies terrain tiles
* and survives serialization. This class validates that the move operation changes the terrain type
* of a specified tile and verifies the move's success status. It also checks serialization resilience
* of the ChangeTileMove instance.
*
* @author John Doe
* @since 1.0
* @see ChangeTileMove
* @see AbstractMoveTestCase
* @see MapFixtureFactory2
* @see Point
*/

Source Code

public class ChangeTileMoveTest extends AbstractMoveTestCase {
@Override
public void testMove() {
Point p = new Point(10, 10);
TerrainTile tile = (TerrainTile) world.getTile(10, 10);
assertTrue(tile.getTerrainTypeID() != 5);
ChangeTileMove move = new ChangeTileMove(world, p, 5);
MoveStatus ms = move.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.message, ms.ok);
tile = (TerrainTile) world.getTile(10, 10);
assertTrue(tile.getTerrainTypeID() == 5);
}
public void testMove2() {
Point p = new Point(10, 10);
ChangeTileMove move = new ChangeTileMove(world, p, 5);
assertSurvivesSerialisation(move);
}
@Override
protected void setupWorld() {
world = MapFixtureFactory2.getCopy();
}
}

RemoveStationMove

Full name: jfreerails.move.RemoveStationMove

Documentation

/**
* This Move removes a station from the station list and from the map.
*
* @author Luke
*
*/

Source Code

/**
* This Move removes a station from the station list and from the map.
*
* @author Luke
*
*/
public class RemoveStationMove extends CompositeMove implements TrackMove {
private static final long serialVersionUID = 3760847865429702969L;
private RemoveStationMove(ArrayList<Move> moves) {
super(moves);
}
static RemoveStationMove getInstance(ReadOnlyWorld w,
ChangeTrackPieceMove removeTrackMove, FreerailsPrincipal principal) {
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
int stationIndex = -1;
while (wi.next()) {
StationModel station = (StationModel) wi.getElement();
if (station.x == removeTrackMove.getLocation().x
&& station.y == removeTrackMove.getLocation().y) {
// We have found the station!
stationIndex = wi.getIndex();
break;
}
}
if (-1 == stationIndex) {
throw new IllegalArgumentException("Could find a station at "
+ removeTrackMove.getLocation().x + ", "
+ removeTrackMove.getLocation().y);
}
StationModel station2remove = (StationModel) w.get(principal,
KEY.STATIONS, stationIndex);
ArrayList<Move> moves = new ArrayList<Move>();
moves.add(removeTrackMove);
moves.add(new RemoveItemFromListMove(KEY.STATIONS, stationIndex,
station2remove, principal));
// Now update any train schedules that include this station.
WorldIterator schedules = new NonNullElements(KEY.TRAIN_SCHEDULES, w,
principal);
while (schedules.next()) {
ImmutableSchedule schedule = (ImmutableSchedule) schedules
.getElement();
if (schedule.stopsAtStation(stationIndex)) {
MutableSchedule mutableSchedule = new MutableSchedule(schedule);
mutableSchedule.removeAllStopsAtStation(stationIndex);
Move changeScheduleMove = new ChangeTrainScheduleMove(schedules
.getIndex(), schedule, mutableSchedule
.toImmutableSchedule(), principal);
moves.add(changeScheduleMove);
}
}
return new RemoveStationMove(moves);
}
public Rectangle getUpdatedTiles() {
TrackMove tm = (TrackMove) getMove(0);
return tm.getUpdatedTiles();
}
}

AbstractMoveTestCase

Full name: jfreerails.move.AbstractMoveTestCase

Documentation

/**
* All TestCases for moves should extend this class.
*
* @author Luke
*
*/

Source Code

/**
* All TestCases for moves should extend this class.
*
* @author Luke
*
*/
public abstract class AbstractMoveTestCase extends TestCase {
private boolean hasSetupBeenCalled = false;
protected World world;
protected AbstractMoveTestCase() {
}
public AbstractMoveTestCase(String str) {
super(str);
}
protected void assertDoMoveFails(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.doMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertTrue("Move went through when it should have failed", !ms.ok);
}
protected void assertDoMoveIsOk(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.doMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals(MoveStatus.MOVE_OK, ms);
}
protected void assertDoThenUndoLeavesWorldUnchanged(Move m) {
try {
World w = getWorld();
World before = (World) Utils.cloneBySerialisation(w);
assertEquals(before, w);
assertTrue(m.doMove(w, Player.AUTHORITATIVE).ok);
World after = (World) Utils.cloneBySerialisation(w);
assertFalse(after.equals(before));
boolean b = m.undoMove(w, Player.AUTHORITATIVE).ok;
assertTrue(b);
assertEquals(before, w);
} catch (Exception e) {
e.printStackTrace();
assertTrue(false);
}
}
/**
* This method asserts that if we serialise then deserialize the specified
* move, the specified move is equal to the deserialized move. The assertion
* depends on the move being serializable and the equals method being
* implemented correctly. Also checks that the hashcode does not change.
*
* @param m
*/
protected void assertSurvivesSerialisation(FreerailsSerializable m) {
assertEquals("Reflexivity violated: the move does not equal itself", m,
m);
try {
Object o = Utils.cloneBySerialisation(m);
assertEquals(m, o);
assertEquals("The hashcodes should be the same!", m.hashCode(), o
.hashCode());
} catch (Exception e) {
e.printStackTrace();
assertTrue(false);
}
}
protected void assertOkAndRepeatable(Move m) {
assertSetupHasBeenCalled();
// Do move
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
// Since it leaves the world unchanged it should also be
// possible to undo it repeatably
assertTryUndoMoveIsOk(m);
assertUndoMoveIsOk(m);
assertTryUndoMoveIsOk(m);
assertUndoMoveIsOk(m);
}
/**
* Generally moves should not be repeatable. For example, if we have just
* removed a piece of track, that piece of track is gone, so we cannot
* remove it again.
*/
protected void assertOkButNotRepeatable(Move m) {
assertSetupHasBeenCalled();
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
assertTryMoveFails(m);
assertDoMoveFails(m);
assertTryUndoMoveIsOk(m);
assertUndoMoveIsOk(m);
assertTryUndoMoveFails(m);
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
}
private void assertSetupHasBeenCalled() {
assertTrue("AbstractMoveTestCase.setUp has not been called!",
hasSetupBeenCalled());
}
protected void assertTryMoveFails(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertTrue("Move went through when it should have failed", !ms.ok);
}
protected void assertTryMoveIsOk(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals("First try failed", MoveStatus.MOVE_OK, ms);
ms = m.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals(
"Second try failed, this suggests that the tryDoMove method failed to leave the world unchanged!",
MoveStatus.MOVE_OK, ms);
}
protected void assertTryUndoMoveFails(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryUndoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertTrue("Move went through when it should have failed", !ms.ok);
}
protected void assertTryUndoMoveIsOk(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryUndoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals("First try failed", MoveStatus.MOVE_OK, ms);
ms = m.tryUndoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals(
"Second try failed, this suggests that the tryDoMove method failed to leave the world unchanged!",
MoveStatus.MOVE_OK, ms);
}
protected void assertUndoMoveFails(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryUndoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertTrue("Move went through when it should have failed", !ms.ok);
}
protected void assertUndoMoveIsOk(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.undoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals(MoveStatus.MOVE_OK, ms);
}
FreerailsPrincipal getPrincipal() {
return world.getPlayer(0).getPrincipal();
}
World getWorld() {
return world;
}
protected boolean hasSetupBeenCalled() {
return hasSetupBeenCalled;
}
protected void setHasSetupBeenCalled(boolean hasSetupBeenCalled) {
this.hasSetupBeenCalled = hasSetupBeenCalled;
}
@Override
protected void setUp() throws Exception {
setHasSetupBeenCalled(true);
setupWorld();
}
protected void setupWorld() {
setWorld(new WorldImpl(10, 10));
// Set the time..
getWorld().set(ITEM.CALENDAR, new GameCalendar(12000, 1840));
getWorld().addPlayer(MapFixtureFactory.TEST_PLAYER);
}
void setWorld(World world) {
this.world = world;
}
public void testMove(){}
protected void assertTrackHere(int x, int y) {
FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
assertTrue(tile.hasTrack());
}
protected void assertTrackHere(PathOnTiles path) {
ImPoint start = path.getStart();
int x = start.x;
int y = start.y;
for (int i = 0; i < path.steps(); i++) {
assertTrackHere(x, y);
Step step = path.getStep(i);
x += step.deltaX;
y += step.deltaY;
assertTrackHere(x, y);
}
}
}

AddTransactionMove

Full name: jfreerails.move.AddTransactionMove

Documentation

/**
* This {@link Move} adds a {@link Transaction} to a players bank account on the
* {@link World} object.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* This {@link Move} adds a {@link Transaction} to a players bank account on the
* {@link World} object.
*
* @author Luke Lindsay
*
*/
public class AddTransactionMove implements Move {
private static final long serialVersionUID = 3976738055925019701L;
private final Transaction transaction;
private final FreerailsPrincipal principal;
/** Whether the move fails if there is not enough cash. */
private final boolean constrained;
public Transaction getTransaction() {
return transaction;
}
@Override
public int hashCode() {
int result;
result = transaction.hashCode();
result = 29 * result + principal.hashCode();
result = 29 * result + (constrained ? 1 : 0);
return result;
}
public AddTransactionMove(FreerailsPrincipal account, Transaction t) {
if (null == t) {
throw new NullPointerException();
}
principal = account;
transaction = t;
constrained = false;
}
public AddTransactionMove(FreerailsPrincipal account, Transaction t,
boolean constrain) {
principal = account;
transaction = t;
constrained = constrain;
if (null == t) {
throw new NullPointerException();
}
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.isPlayer(principal)) {
if (this.constrained) {
long bankBalance = w.getCurrentBalance(principal).getAmount();
long transactionAmount = this.transaction.deltaCash()
.getAmount();
long balanceAfter = bankBalance + transactionAmount;
if (transactionAmount < 0 && balanceAfter < 0) {
return MoveStatus.moveFailed("You can't afford that!");
}
}
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed(p.getName()
+ " does not have a bank account.");
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int size = w.getNumberOfTransactions(this.principal);
if (0 == size) {
return MoveStatus.moveFailed("No transactions to remove!");
}
Transaction lastTransaction = w
.getTransaction(this.principal, size - 1);
if (lastTransaction.equals(this.transaction)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + this.transaction
+ "but found " + lastTransaction);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.ok) {
w.addTransaction(this.principal, this.transaction);
}
return ms;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.ok) {
w.removeLastTransaction(this.principal);
}
return ms;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AddTransactionMove) {
AddTransactionMove test = (AddTransactionMove) obj;
return test.principal.equals(this.principal)
&& test.transaction.equals(this.transaction);
}
return false;
}
public FreerailsPrincipal getPrincipal() {
return principal;
}
}

WorldDiffsMoveTest

Full name: jfreerails.move.WorldDiffsMoveTest

Documentation

/**
* Tests the functionality of the WorldDiffs and WorldDiffMove classes to ensure they correctly capture, apply, and undo changes to the world state.
* This class verifies scenarios such as modifying tiles, lists, transactions, and activities, ensuring diffs are accurately tracked and moves are serialized and reversible.
*
* @author John Doe
* @see WorldDiffs
* @see WorldDiffMove
* @see World
* @see Transaction
* @see Activity
*/

Source Code

public class WorldDiffsMoveTest extends TestCase {
World world;
WorldDiffs diffs;
FreerailsPrincipal fp1;
CityModel city1 = new CityModel("City 1", 8, 4);
CityModel city2 = new CityModel("City 2", 9, 4);
@Override
protected void setUp() throws Exception {
world = new WorldImpl(10, 10);
// Set the time..
world.set(ITEM.CALENDAR, new GameCalendar(12000, 1840));
world.addPlayer(MapFixtureFactory.TEST_PLAYER);
fp1 = world.getPlayer(0).getPrincipal();
diffs = new WorldDiffs(world);
}
public void testChangingMap() {
diffs.setTile(4, 0, city1);
diffs.setTile(8, 5, city2);
runTests();
}
public void testChangingElementInList1() {
world.add(fp1, KEY.STATIONS, city1);
world.add(fp1, KEY.STATIONS, city1);
diffs.set(fp1, KEY.STATIONS, 0, city2);
diffs.set(fp1, KEY.STATIONS, 1, city2);
runTests();
}
public void testChangingElementInList2() {
world.add(fp1, KEY.STATIONS, city1);
world.add(fp1, KEY.STATIONS, city1);
diffs.set(fp1, KEY.STATIONS, 0, city2);
diffs.set(fp1, KEY.STATIONS, 1, city2);
assertEquals(2, diffs.listDiffs());
WorldDiffMove move = WorldDiffMove.generate(diffs, WorldDiffMove.Cause.Other);
assertEquals(2, move.listDiffs());
}
public void testAddingElementToList() {
world.add(fp1, KEY.STATIONS, city1);
diffs.add(fp1, KEY.STATIONS, city2);
diffs.add(fp1, KEY.STATIONS, city2);
diffs.add(fp1, KEY.STATIONS, city2);
runTests();
}
public void testAddingTransaction() {
Transaction t1 = new AddItemTransaction(Category.BOND, 1, 1, new Money(
100));
Transaction t2 = new AddItemTransaction(Category.BOND, 2, 2, new Money(
1000));
Transaction t3 = new AddItemTransaction(Category.BOND, 3, 3, new Money(
10000));
world.addTransaction(fp1, t1);
diffs.addTransaction(fp1, t2);
diffs.addTransaction(fp1, t3);
runTests();
}
public void testAddingActivity(){
Activity act = new TestActivity(30);
int row = world.addActiveEntity(fp1, act);
act = new TestActivity(40);
world.add(fp1, row, act);
act = new TestActivity(50);
diffs.add(fp1, row, act);
runTests();
}
public void testAddingActivateEntity() {
Activity act = new TestActivity(30);
int row = world.addActiveEntity(fp1, act);
act = new TestActivity(40);
world.add(fp1, row, act);
act = new TestActivity(50);
diffs.add(fp1, row, act);
act = new TestActivity(60);
row = diffs.addActiveEntity(fp1, act);
act = new TestActivity(70);
diffs.add(fp1, row, act);
act = new TestActivity(80);
row = diffs.addActiveEntity(fp1, act);
act = new TestActivity(90);
diffs.add(fp1, row, act);
runTests();
}
void runTests() {
assertFalse(diffs.equals(world));
WorldDiffMove move = WorldDiffMove.generate(diffs, WorldDiffMove.Cause.Other);
// Doing the move on the world should also succeed.
World worldCopy = (World) Utils.cloneBySerialisation(world);
assertEquals(worldCopy, world);
MoveStatus ms = move.tryDoMove(worldCopy, fp1);
if(!ms.ok)
ms.printStackTrack();
assertTrue(ms.message, ms.ok);
ms = move.doMove(worldCopy, fp1);
assertTrue(ms.ok);
assertEquals(worldCopy, diffs);
// Undoing the move on the diffs should succeed.
WorldDiffs diffsCopy = (WorldDiffs) Utils.cloneBySerialisation(diffs);
assertEquals(diffsCopy, diffs);
ms = move.tryUndoMove(diffsCopy, fp1);
assertTrue(ms.message, ms.ok);
assertFalse(diffsCopy.equals(world));
ms = move.undoMove(diffsCopy, fp1);
assertTrue(ms.ok);
assertEquals(diffsCopy, world);
// The move should survive serialisation.
Object moveCopy = Utils.cloneBySerialisation(move);
assertEquals(moveCopy, move);
assertEquals(moveCopy.hashCode(), move.hashCode());
}
}

CompositeMove

Full name: jfreerails.move.CompositeMove

Documentation

/**
*
* This Move may be subclassed to create a move composed of a number of
* component Moves where atomicity of the move is required. This class defines a
* number of methods which may not be subclassed - all changes must be
* encapsulated as sub-moves of this move.
*
* @author Luke
*/

Source Code

/**
*
* This Move may be subclassed to create a move composed of a number of
* component Moves where atomicity of the move is required. This class defines a
* number of methods which may not be subclassed - all changes must be
* encapsulated as sub-moves of this move.
*
* @author Luke
*/
public class CompositeMove implements Move {
private static final long serialVersionUID = 3257289149391517489L;
private final ImList<Move> moves;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof CompositeMove))
return false;
final CompositeMove compositeMove = (CompositeMove) o;
if (!moves.equals(compositeMove.moves))
return false;
return true;
}
/**
* This method lets sub classes look at the moves.
*/
final Move getMove(int i) {
return moves.get(i);
}
@Override
public int hashCode() {
// This will do for now.
return moves.size();
}
public final ImList<Move> getMoves() {
return moves;
}
public CompositeMove(List<Move> movesArrayList) {
moves = new ImList<Move>(movesArrayList);
}
public CompositeMove(Move... moves) {
this.moves = new ImList<Move>(moves);
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
// Since whether a move later in the list goes through could
// depend on whether an earlier move has been executed, we need
// actually execute moves, then undo them to test whether the
// array of moves can be executed ok.
MoveStatus ms = doMove(w, p);
if (ms.ok) {
// We just wanted to see if we could do them so we undo them again.
undoMoves(w, moves.size() - 1, p);
}
// If its not ok, then doMove would have undone the moves so we don't
// need to undo them.
return ms;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = undoMove(w, p);
if (ms.isOk()) {
redoMoves(w, 0, p);
}
return ms;
}
public final MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = compositeTest(w, p);
if (!ms.ok) {
return ms;
}
for (int i = 0; i < moves.size(); i++) {
ms = moves.get(i).doMove(w, p);
if (!ms.ok) {
// Undo any moves we have already done.
undoMoves(w, i - 1, p);
return ms;
}
}
return ms;
}
public final MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = MoveStatus.MOVE_OK;
for (int i = moves.size() - 1; i >= 0; i--) {
ms = moves.get(i).undoMove(w, p);
if (!ms.ok) {
// Redo any moves we have already undone.
redoMoves(w, i + 1, p);
return ms;
}
}
return ms;
}
private void undoMoves(World w, int number, FreerailsPrincipal p) {
for (int i = number; i >= 0; i--) {
MoveStatus ms = moves.get(i).undoMove(w, p);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
}
}
private void redoMoves(World w, int number, FreerailsPrincipal p) {
for (int i = number; i < moves.size(); i++) {
MoveStatus ms = moves.get(i).doMove(w, p);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
}
}
/**
* Subclasses may override this method to perform tests which pass or fail
* depending on the combination of moves making up this composite move.
*/
MoveStatus compositeTest(World w, FreerailsPrincipal p) {
return MoveStatus.MOVE_OK;
}
public int size(){
return moves.size();
}
@Override
public final String toString() {
String s = "";
for (int i = 0; i < moves.size(); i++) {
s += moves.get(i).toString() + ((i > 0) ? ", " : "");
}
return s;
}
}

AddTransactionMoveTest

Full name: jfreerails.move.AddTransactionMoveTest

Documentation

/**
* JUnit test.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* JUnit test.
*
* @author Luke Lindsay
*
*/
public class AddTransactionMoveTest extends AbstractMoveTestCase {
@Override
public void testMove() {
Money currentBalance = getWorld().getCurrentBalance(
MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(new Money(0), currentBalance);
Transaction t = new Receipt(new Money(100),
Transaction.Category.MISC_INCOME);
Move m = new AddTransactionMove(MapFixtureFactory.TEST_PRINCIPAL, t);
assertTryMoveIsOk(m);
assertTryUndoMoveFails(m);
assertDoMoveIsOk(m);
currentBalance = getWorld().getCurrentBalance(
MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(new Money(100), currentBalance);
final Player PLAYER_WITHOUT_ACCOUNT = new Player(
"PLAYER_WITHOUT_ACCOUNT", 4);
assertSurvivesSerialisation(m);
Move m2 = new AddTransactionMove(PLAYER_WITHOUT_ACCOUNT.getPrincipal(),
t);
assertTryMoveFails(m2);
assertOkAndRepeatable(m);
}
public void testConstrainedMove() {
Money currentBalance = getWorld().getCurrentBalance(
MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(new Money(0), currentBalance);
Transaction t = new Bill(new Money(100),
Transaction.Category.MISC_INCOME);
Move m = new AddTransactionMove(MapFixtureFactory.TEST_PRINCIPAL, t,
true);
// This move should fail since there is no money in the account and
// it is constrained is set to true.
assertTryMoveFails(m);
}
}

TrackMove

Full name: jfreerails.move.TrackMove

Documentation

/**
* This interface tags Moves that change the track.
*
* @author luke
*/

Source Code

/**
* This interface tags Moves that change the track.
*
* @author luke
*/
public interface TrackMove extends MapUpdateMove {
}

Methods

No methods found

ChangeProductionAtEngineShopMoveTest

Full name: jfreerails.move.ChangeProductionAtEngineShopMoveTest

Documentation

/**
* Junit TestCase for ChangeProductionAtEngineShopMove.
*
* @author Luke
*
*/

Source Code

/**
* Junit TestCase for ChangeProductionAtEngineShopMove.
*
* @author Luke
*
*/
public class ChangeProductionAtEngineShopMoveTest extends AbstractMoveTestCase {
private ImList<PlannedTrain> before;
private ImList<PlannedTrain> after;
private int engineType;
private int wagonType;
private int[] wagons;
@Override
protected void setUp() throws Exception {
super.setUp();
getWorld().add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
new StationModel());
getWorld().add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
new StationModel());
getWorld().add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
new StationModel());
WagonAndEngineTypesFactory wetf = new WagonAndEngineTypesFactory();
wetf.addTypesToWorld(getWorld());
engineType = 0;
wagonType = 0;
wagons = new int[] { wagonType, wagonType };
after = new ImList<PlannedTrain>(new PlannedTrain(
engineType, wagons));
}
@Override
public void testMove() {
before = new ImList<PlannedTrain>();
ChangeProductionAtEngineShopMove m;
// Should fail because current production at station 0 is null;
m = new ChangeProductionAtEngineShopMove(after, before, 0,
MapFixtureFactory.TEST_PRINCIPAL);
assertTryMoveFails(m);
assertDoMoveFails(m);
// Should fail because station 6 does not exist.
m = new ChangeProductionAtEngineShopMove(before, after, 6,
MapFixtureFactory.TEST_PRINCIPAL);
assertTryMoveFails(m);
assertDoMoveFails(m);
// Should go through
m = new ChangeProductionAtEngineShopMove(before, after, 0,
MapFixtureFactory.TEST_PRINCIPAL);
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
assertTryUndoMoveIsOk(m);
assertUndoMoveIsOk(m);
// It should not be repeatable.
assertOkButNotRepeatable(m);
assertSurvivesSerialisation(m);
}
public void testProductionAtEngineShopEquals() {
PlannedTrain b;
PlannedTrain c;
b = new PlannedTrain(engineType, wagons);
c = new PlannedTrain(engineType, wagons);
assertEquals(c, b);
assertEquals(b, c);
}
}

ChangeGameSpeedMove

Full name: jfreerails.move.ChangeGameSpeedMove

Documentation

/**
*
* Changes the game speed item on the world object.
*
* @author Jan Tozicka
*
*/

Source Code

/**
*
* Changes the game speed item on the world object.
*
* @author Jan Tozicka
*
*/
public class ChangeGameSpeedMove implements Move {
private static final long serialVersionUID = 3545794368956086071L;
private final GameSpeed oldSpeed;
private final GameSpeed newSpeed;
public static ChangeGameSpeedMove getMove(ReadOnlyWorld w,
GameSpeed newGameSpeed) {
return new ChangeGameSpeedMove((GameSpeed) w.get(ITEM.GAME_SPEED),
newGameSpeed);
}
private ChangeGameSpeedMove(GameSpeed before, GameSpeed after) {
oldSpeed = before;
newSpeed = after;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.get(ITEM.GAME_SPEED).equals(oldSpeed)) {
return MoveStatus.MOVE_OK;
}
String string = "oldSpeed = " + oldSpeed.getSpeed() + " <=> "
+ "currentSpeed "
+ ((GameSpeed) w.get(ITEM.GAME_SPEED)).getSpeed();
return MoveStatus.moveFailed(string);
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
GameSpeed speed = ((GameSpeed) w.get(ITEM.GAME_SPEED));
if (speed.equals(newSpeed)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + newSpeed + ", found "
+ speed);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryDoMove(w, p);
if (status.ok) {
w.set(ITEM.GAME_SPEED, newSpeed);
}
return status;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryUndoMove(w, p);
if (status.isOk()) {
w.set(ITEM.GAME_SPEED, oldSpeed);
}
return status;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ChangeGameSpeedMove))
return false;
final ChangeGameSpeedMove changeGameSpeedMove = (ChangeGameSpeedMove) o;
if (!newSpeed.equals(changeGameSpeedMove.newSpeed))
return false;
if (!oldSpeed.equals(changeGameSpeedMove.oldSpeed))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = oldSpeed.hashCode();
result = 29 * result + newSpeed.hashCode();
return result;
}
public int getNewSpeed() {
return newSpeed.getSpeed();
}
@Override
public String toString() {
return "ChangeGameSpeedMove: " + oldSpeed + "=>" + newSpeed;
}
}

AddCargoBundleMoveTest

Full name: jfreerails.move.AddCargoBundleMoveTest

Documentation

/**
* JUnit test.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test.
*
* @author Luke
*
*/
public class AddCargoBundleMoveTest extends AbstractMoveTestCase {
@Override
public void testMove() {
MutableCargoBundle bundleA;
MutableCargoBundle bundleB;
bundleA = new MutableCargoBundle();
bundleB = new MutableCargoBundle();
bundleA.setAmount(new CargoBatch(1, 2, 3, 4, 0), 5);
bundleB.setAmount(new CargoBatch(1, 2, 3, 4, 0), 5);
assertEquals(bundleA, bundleB);
Move m = new AddCargoBundleMove(0, bundleA.toImmutableCargoBundle(),
MapFixtureFactory.TEST_PRINCIPAL);
assertDoMoveIsOk(m);
assertEquals(getWorld().size(MapFixtureFactory.TEST_PRINCIPAL,
KEY.CARGO_BUNDLES), 1);
assertUndoMoveIsOk(m);
assertSurvivesSerialisation(m);
assertOkButNotRepeatable(m);
}
}

Methods

ChangeStationMove

Full name: jfreerails.move.ChangeStationMove

Documentation

/**
*
* This Move changes the properties of a station.
*
* @author lindsal
*/

Source Code

/**
*
* This Move changes the properties of a station.
*
* @author lindsal
*/
final public class ChangeStationMove extends ChangeItemInListMove {
private static final long serialVersionUID = 3833469496064160307L;
public ChangeStationMove(int index, StationModel before,
StationModel after, FreerailsPrincipal p) {
super(KEY.STATIONS, index, before, after, p);
}
}

ChangeProductionAtEngineShopMove

Full name: jfreerails.move.ChangeProductionAtEngineShopMove

Documentation

/**
* This Move changes what is being built at an engine shop - when a client wants
* to build a train, it should send an instance of this class to the server.
*
* @author Luke
*
*/

Source Code

/**
* This Move changes what is being built at an engine shop - when a client wants
* to build a train, it should send an instance of this class to the server.
*
* @author Luke
*
*/
public class ChangeProductionAtEngineShopMove implements Move {
private static final long serialVersionUID = 3905519384997737520L;
private final ImList<PlannedTrain> before;
private final ImList<PlannedTrain> after;
private final int stationNumber;
private final FreerailsPrincipal principal;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ChangeProductionAtEngineShopMove))
return false;
final ChangeProductionAtEngineShopMove changeProductionAtEngineShopMove = (ChangeProductionAtEngineShopMove) o;
if (stationNumber != changeProductionAtEngineShopMove.stationNumber)
return false;
if (after != null ? !after
.equals(changeProductionAtEngineShopMove.after)
: changeProductionAtEngineShopMove.after != null)
return false;
if (before != null ? !before
.equals(changeProductionAtEngineShopMove.before)
: changeProductionAtEngineShopMove.before != null)
return false;
if (!principal.equals(changeProductionAtEngineShopMove.principal))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = (before != null ? before.hashCode() : 0);
result = 29 * result + (after != null ? after.hashCode() : 0);
result = 29 * result + stationNumber;
result = 29 * result + principal.hashCode();
return result;
}
public ChangeProductionAtEngineShopMove(ImList<PlannedTrain> b,
ImList<PlannedTrain> a, int station, FreerailsPrincipal p) {
this.before = b;
this.after = a;
this.stationNumber = station;
this.principal = p;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
return tryMove(w, before);
}
private MoveStatus tryMove(World w, ImList<PlannedTrain> stateA) {
// Check that the specified station exists.
if (!w.boundsContain(principal, KEY.STATIONS, this.stationNumber)) {
return MoveStatus.moveFailed(this.stationNumber + " " + principal);
}
StationModel station = (StationModel) w.get(principal, KEY.STATIONS,
stationNumber);
if (null == station) {
return MoveStatus.moveFailed(this.stationNumber + " " + principal
+ " is does null");
}
// Check that the station is building what we expect.
if (null == station.getProduction()) {
if (null == stateA) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed(this.stationNumber + " " + principal);
}
if (station.getProduction().equals(stateA)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed(this.stationNumber + " " + principal);
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
return tryMove(w, after);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryDoMove(w, p);
if (status.isOk()) {
StationModel station = (StationModel) w.get(principal,
KEY.STATIONS, stationNumber);
station = new StationModel(station, this.after);
w.set(principal, KEY.STATIONS, stationNumber, station);
}
return status;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryUndoMove(w, p);
if (status.isOk()) {
StationModel station = (StationModel) w.get(principal,
KEY.STATIONS, stationNumber);
station = new StationModel(station, this.before);
w.set(principal, KEY.STATIONS, stationNumber, station);
}
return status;
}
}

ChangeItemInListMove

Full name: jfreerails.move.ChangeItemInListMove

Documentation

/**
* All Moves that replace an item in a list with another should extend this
* class.
*
* @author Luke
*
*/

Source Code

/**
* All Moves that replace an item in a list with another should extend this
* class.
*
* @author Luke
*
*/
public class ChangeItemInListMove implements ListMove {
private static final long serialVersionUID = -4457694821370844051L;
private final KEY listKey;
private final int index;
private final FreerailsSerializable before;
private final FreerailsSerializable after;
private final FreerailsPrincipal principal;
public ChangeItemInListMove(KEY k, int index, FreerailsSerializable before,
FreerailsSerializable after, FreerailsPrincipal p) {
this.before = before;
this.after = after;
this.index = index;
this.listKey = k;
this.principal = p;
}
public boolean beforeEqualsAfter(){
return Utils.equal(this.before, this.after);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
return move(after, before, w);
}
@Override
public boolean equals(Object o) {
if (o instanceof ChangeItemInListMove) {
ChangeItemInListMove test = (ChangeItemInListMove) o;
if (!before.equals(test.getBefore())) {
return false;
}
if (!after.equals(test.getAfter())) {
return false;
}
if (index != test.index) {
return false;
}
if (listKey != test.listKey) {
return false;
}
return true;
}
return false;
}
public FreerailsSerializable getAfter() {
return after;
}
public FreerailsSerializable getBefore() {
return before;
}
public int getIndex() {
return index;
}
public KEY getKey() {
return listKey;
}
public FreerailsPrincipal getPrincipal() {
return principal;
}
@Override
public int hashCode() {
int result;
result = listKey.hashCode();
result = 29 * result + index;
result = 29 * result + (before != null ? before.hashCode() : 0);
result = 29 * result + (after != null ? after.hashCode() : 0);
result = 29 * result + principal.hashCode();
return result;
}
protected MoveStatus move(FreerailsSerializable to,
FreerailsSerializable from, World w) {
MoveStatus ms = tryMove(to, from, w);
if (ms.ok) {
w.set(principal, listKey, index, to);
}
return ms;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(getClass().getName());
sb.append(" before: ");
sb.append(before.toString());
sb.append(" after: ");
sb.append(after.toString());
return sb.toString();
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
return tryMove(after, before, w);
}
protected MoveStatus tryMove(FreerailsSerializable to,
FreerailsSerializable from, World w) {
if (index >= w.size(principal, listKey)) {
return MoveStatus.moveFailed("w.size(listKey) is "
+ w.size(principal, listKey) + " but index is " + index);
}
FreerailsSerializable item2change = w.get(principal, listKey, index);
if (null == item2change) {
if (null == from) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected null but found " + from);
}
if (!from.equals(item2change)) {
String message = "Expected " + from.toString() + " but found "
+ to.toString();
return MoveStatus.moveFailed(message);
}
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
return tryMove(before, after, w);
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
return move(before, after, w);
}
}

ChangeTrackPieceCompositeMove

Full name: jfreerails.move.ChangeTrackPieceCompositeMove

Documentation

/**
* This Move changes adds, removes, or upgrades the track between two tiles.
*
* @author lindsal
*
*/

Source Code

/**
* This Move changes adds, removes, or upgrades the track between two tiles.
*
* @author lindsal
*
*/
public final class ChangeTrackPieceCompositeMove extends CompositeMove
implements TrackMove, MapUpdateMove {
private static final long serialVersionUID = 3616443518780978743L;
private final int x, y, w, h;
private final FreerailsPrincipal builder;
private ChangeTrackPieceCompositeMove(TrackMove a, TrackMove b,
FreerailsPrincipal fp) {
super(a, b);
Rectangle r = a.getUpdatedTiles().union(b.getUpdatedTiles());
x = r.x;
y = r.y;
w = r.width;
h = r.height;
builder = fp;
}
public static ChangeTrackPieceCompositeMove generateBuildTrackMove(
ImPoint from, Step direction, TrackRule ruleA, TrackRule ruleB,
ReadOnlyWorld w, FreerailsPrincipal principal) {
ChangeTrackPieceMove a;
ChangeTrackPieceMove b;
a = getBuildTrackChangeTrackPieceMove(from, direction, ruleA, w,
principal);
b = getBuildTrackChangeTrackPieceMove(direction
.createRelocatedPoint(from), direction.getOpposite(), ruleB, w,
principal);
return new ChangeTrackPieceCompositeMove(a, b, principal);
}
public static ChangeTrackPieceCompositeMove generateRemoveTrackMove(
ImPoint from, Step direction, ReadOnlyWorld w,
FreerailsPrincipal principal) throws Exception {
TrackMove a;
TrackMove b;
a = getRemoveTrackChangeTrackPieceMove(from, direction, w, principal);
b = getRemoveTrackChangeTrackPieceMove(direction
.createRelocatedPoint(from), direction.getOpposite(), w,
principal);
return new ChangeTrackPieceCompositeMove(a, b, principal);
}
// utility method.
private static ChangeTrackPieceMove getBuildTrackChangeTrackPieceMove(
ImPoint p, Step direction, TrackRule trackRule, ReadOnlyWorld w,
FreerailsPrincipal principal) {
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
int owner = getOwner(principal, w);
if (w.boundsContain(p.x, p.y)) {
oldTrackPiece = ((FreerailsTile) w.getTile(p.x, p.y))
.getTrackPiece();
if (oldTrackPiece.getTrackRule() != NullTrackType.getInstance()) {
TrackConfiguration trackConfiguration = TrackConfiguration.add(
oldTrackPiece.getTrackConfiguration(), direction);
newTrackPiece = new TrackPieceImpl(trackConfiguration,
oldTrackPiece.getTrackRule(), owner, oldTrackPiece
.getTrackTypeID());
} else {
newTrackPiece = getTrackPieceWhenOldTrackPieceIsNull(direction,
trackRule, owner, findRuleID(trackRule, w));
}
} else {
newTrackPiece = getTrackPieceWhenOldTrackPieceIsNull(direction,
trackRule, owner, findRuleID(trackRule, w));
oldTrackPiece = NullTrackPiece.getInstance();
}
return new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece, p);
}
// utility method.
private static TrackMove getRemoveTrackChangeTrackPieceMove(ImPoint p,
Step direction, ReadOnlyWorld w, FreerailsPrincipal principal)
throws Exception {
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
if (w.boundsContain(p.x, p.y)) {
oldTrackPiece = ((FreerailsTile) w.getTile(p.x, p.y)).getTrackPiece();
if (oldTrackPiece.getTrackRule() != NullTrackType.getInstance()) {
TrackConfiguration trackConfiguration = TrackConfiguration
.subtract(oldTrackPiece.getTrackConfiguration(),
direction);
if (trackConfiguration != TrackConfiguration
.getFlatInstance("000010000")) {
int owner = getOwner(principal, w);
newTrackPiece = new TrackPieceImpl(trackConfiguration,
oldTrackPiece.getTrackRule(), owner, oldTrackPiece
.getTrackTypeID());
} else {
newTrackPiece = NullTrackPiece.getInstance();
}
} else {
// There is no track to remove.
// Fix for bug [ 948670 ] Removing non-existent track
throw new Exception();
}
} else {
newTrackPiece = NullTrackPiece.getInstance();
oldTrackPiece = NullTrackPiece.getInstance();
}
ChangeTrackPieceMove m = new ChangeTrackPieceMove(oldTrackPiece,
newTrackPiece, p);
// If we are removing a station, we also need to remove the station from
// the station list.
if (oldTrackPiece.getTrackRule().isStation()
&& !newTrackPiece.getTrackRule().isStation()) {
return RemoveStationMove.getInstance(w, m, principal);
}
return m;
}
private static TrackPiece getTrackPieceWhenOldTrackPieceIsNull(
Step direction, TrackRule trackRule, int owner, int ruleNumber) {
TrackConfiguration simplestConfig = TrackConfiguration
.getFlatInstance("000010000");
TrackConfiguration trackConfiguration = TrackConfiguration.add(
simplestConfig, direction);
return new TrackPieceImpl(trackConfiguration, trackRule, owner,
ruleNumber);
}
public Rectangle getUpdatedTiles() {
return new Rectangle(x, y, w, h);
}
public static int getOwner(FreerailsPrincipal p, ReadOnlyWorld w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
if (w.getPlayer(i).getPrincipal().equals(p)) {
return i;
}
}
throw new IllegalStateException();
}
/** Returns true if some track has been built. */
static boolean hasAnyTrackBeenBuilt(ReadOnlyWorld world,
FreerailsPrincipal principal) {
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
world, principal);
aggregator.setCategory(Transaction.Category.TRACK);
return aggregator.calculateQuantity() > 0;
}
private static boolean mustConnectToExistingTrack(ReadOnlyWorld world) {
GameRules rules = (GameRules) world.get(ITEM.GAME_RULES);
return rules.isMustConnect2ExistingTrack();
}
@Override
protected MoveStatus compositeTest(World world, FreerailsPrincipal p) {
if (mustConnectToExistingTrack(world)) {
if (hasAnyTrackBeenBuilt(world, this.builder)) {
try {
ChangeTrackPieceMove a = (ChangeTrackPieceMove) super
.getMove(0);
ChangeTrackPieceMove b = (ChangeTrackPieceMove) super
.getMove(1);
int ruleBeforeA = a.trackPieceBefore.getTrackTypeID();
int ruleBeforeB = b.trackPieceBefore.getTrackTypeID();
if (ruleBeforeA == NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER
&& ruleBeforeB == NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
return MoveStatus
.moveFailed("Must connect to existing track");
}
} catch (ClassCastException e) {
// It was not the type of move we expected.
// We end up here when we are removing a station.
return MoveStatus.MOVE_OK;
}
}
}
return MoveStatus.MOVE_OK;
}
public static int findRuleID(TrackRule r, ReadOnlyWorld w) {
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
Object o = w.get(SKEY.TRACK_RULES, i);
if (r.equals(o)) {
return i;
}
}
throw new IllegalStateException();
}
}

RemoveCargoBundleMove

Full name: jfreerails.move.RemoveCargoBundleMove

Documentation

/**
* This move removes a cargo bundle from the cargo bundle list.
*
* @author Luke
*
*/

Source Code

/**
* This move removes a cargo bundle from the cargo bundle list.
*
* @author Luke
*
*/
public class RemoveCargoBundleMove extends RemoveItemFromListMove {
private static final long serialVersionUID = 3762247522239723316L;
public RemoveCargoBundleMove(int i, ImmutableCargoBundle item,
FreerailsPrincipal p) {
super(KEY.CARGO_BUNDLES, i, item, p);
}
}

AddCargoBundleMove

Full name: jfreerails.move.AddCargoBundleMove

Documentation

/**
* This Move adds a cargo bundle to the cargo bundle list.
*
* @author Luke
*
*/

Source Code

/**
* This Move adds a cargo bundle to the cargo bundle list.
*
* @author Luke
*
*/
public class AddCargoBundleMove extends AddItemToListMove {
private static final long serialVersionUID = 3257288049795674934L;
public AddCargoBundleMove(int i, ImmutableCargoBundle item,
FreerailsPrincipal p) {
super(KEY.CARGO_BUNDLES, i, item, p);
}
}

PreMoveException

Full name: jfreerails.move.PreMoveException

Documentation

/**
* Thrown when there is a problem generating a move.
*
* @author Luke Lindsay
*
*
*/

Source Code

/**
* Thrown when there is a problem generating a move.
*
* @author Luke Lindsay
*
*
*/
public class PreMoveException extends Exception {
private static final long serialVersionUID = 3257007635675755061L;
public PreMoveException(String s) {
super(s);
}
}

ChangeTileMove

Full name: jfreerails.move.ChangeTileMove

Documentation

/**
* Move that changes a single tile.
*
* @author Luke
*
*/

Source Code

/**
* Move that changes a single tile.
*
* @author Luke
*
*/
public class ChangeTileMove implements Move, MapUpdateMove {
private static final long serialVersionUID = 3256726169272662320L;
private final int x;
private final int y;
private final FreerailsTile before;
private final FreerailsTile after;
public ChangeTileMove(ReadOnlyWorld w, Point p, int terrainTypeAfter) {
this.x = p.x;
this.y = p.y;
this.before = (FreerailsTile) w.getTile(x, y);
this.after = FreerailsTile.getInstance(terrainTypeAfter, before
.getTrackPiece());
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ChangeTileMove))
return false;
final ChangeTileMove changeTileMove = (ChangeTileMove) o;
if (x != changeTileMove.x)
return false;
if (y != changeTileMove.y)
return false;
if (!after.equals(changeTileMove.after))
return false;
if (!before.equals(changeTileMove.before))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = x;
result = 29 * result + y;
result = 29 * result + before.hashCode();
result = 29 * result + after.hashCode();
return result;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
FreerailsTile actual = (FreerailsTile) w.getTile(x, y);
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES, actual
.getTerrainTypeID());
if (!type.getCategory().equals(TerrainType.Category.Country)) {
return MoveStatus.moveFailed("Can only build on clear terrain.");
}
if (actual.equals(before)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + before + " but found "
+ actual);
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
FreerailsTile actual = (FreerailsTile) w.getTile(x, y);
if (actual.equals(after)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + after + " but found "
+ actual);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.isOk()) {
w.setTile(x, y, after);
}
return ms;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.isOk()) {
w.setTile(x, y, before);
}
return ms;
}
public Rectangle getUpdatedTiles() {
Rectangle r = new Rectangle(x, y, 1, 1);
return r;
}
}

AddItemToListMove

Full name: jfreerails.move.AddItemToListMove

Documentation

/**
* All moves that add an item to a list should extend this class.
*
* @author Luke
*
*/

Source Code

/**
* All moves that add an item to a list should extend this class.
*
* @author Luke
*
*/
public class AddItemToListMove implements ListMove {
private static final long serialVersionUID = 3256721779916747824L;
private final KEY listKey;
private final int index;
private final FreerailsPrincipal principal;
private final FreerailsSerializable item;
public int getIndex() {
return index;
}
@Override
public int hashCode() {
int result;
result = listKey.hashCode();
result = 29 * result + index;
result = 29 * result + principal.hashCode();
result = 29 * result + (item != null ? item.hashCode() : 0);
return result;
}
public KEY getKey() {
return listKey;
}
public AddItemToListMove(KEY key, int i, FreerailsSerializable item,
FreerailsPrincipal p) {
this.listKey = key;
this.index = i;
this.item = item;
this.principal = p;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.size(this.principal, listKey) != index) {
return MoveStatus.moveFailed("Expected size of "
+ listKey.toString() + " list is " + index
+ " but actual size is " + w.size(this.principal, listKey));
}
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int expectListSize = index + 1;
if (w.size(this.principal, listKey) != expectListSize) {
return MoveStatus.moveFailed("Expected size of "
+ listKey.toString() + " list is " + expectListSize
+ " but actual size is " + w.size(this.principal, listKey));
}
return MoveStatus.MOVE_OK;
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.isOk()) {
w.add(this.principal, listKey, this.item);
}
return ms;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.isOk()) {
w.removeLast(this.principal, listKey);
}
return ms;
}
@Override
public boolean equals(Object o) {
if (o instanceof AddItemToListMove) {
AddItemToListMove test = (AddItemToListMove) o;
if (null == this.item) {
if (null != test.item) {
return false;
}
} else if (!this.item.equals(test.getAfter())) {
return false;
}
if (this.index != test.index) {
return false;
}
if (this.listKey != test.listKey) {
return false;
}
return true;
}
return false;
}
public FreerailsSerializable getBefore() {
return null;
}
public FreerailsSerializable getAfter() {
return item;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer(this.getClass().getName());
sb.append("\n list=");
sb.append(listKey.toString());
sb.append("\n index =");
sb.append(index);
sb.append("\n item =");
sb.append(item);
return sb.toString();
}
public FreerailsPrincipal getPrincipal() {
return principal;
}
}

RemoveItemFromListMove

Full name: jfreerails.move.RemoveItemFromListMove

Documentation

/**
* All moves that remove an item from a list should extend this class.
*
* @author Luke
*
*/

Source Code

/**
* All moves that remove an item from a list should extend this class.
*
* @author Luke
*
*/
public class RemoveItemFromListMove implements ListMove {
private static final long serialVersionUID = 3906091169698953521L;
private final FreerailsSerializable item;
private final KEY listKey;
private final int index;
private final FreerailsPrincipal principal;
public int getIndex() {
return index;
}
@Override
public int hashCode() {
int result;
result = (item != null ? item.hashCode() : 0);
result = 29 * result + listKey.hashCode();
result = 29 * result + index;
result = 29 * result + principal.hashCode();
return result;
}
public KEY getKey() {
return listKey;
}
RemoveItemFromListMove(KEY k, int i, FreerailsSerializable item,
FreerailsPrincipal p) {
this.item = item;
this.listKey = k;
this.index = i;
this.principal = p;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.size(principal, listKey) < (index + 1)) {
return MoveStatus.moveFailed("w.size(listKey)="
+ w.size(principal, listKey) + " but index =" + index);
}
FreerailsSerializable item2remove = w.get(principal, listKey, index);
if (null == item2remove) {
return MoveStatus.moveFailed("The item at position " + index
+ " has already been removed.");
}
if (!item.equals(item2remove)) {
String reason = "The item at position " + index + " in the list ("
+ item2remove.toString() + ") is not the expected item ("
+ item.toString() + ").";
return MoveStatus.moveFailed(reason);
}
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
if (w.size(principal, listKey) < (index + 1)) {
return MoveStatus.moveFailed("w.size(listKey)="
+ w.size(principal, listKey) + " but index =" + index);
}
if (null != w.get(principal, listKey, index)) {
String reason = "The item at position " + index + " in the list ("
+ w.get(principal, listKey, index).toString()
+ ") is not the expected item (null).";
return MoveStatus.moveFailed(reason);
}
return MoveStatus.MOVE_OK;
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.isOk()) {
w.set(principal, listKey, index, null);
}
return ms;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.isOk()) {
w.set(principal, listKey, index, this.item);
}
return ms;
}
@Override
public boolean equals(Object o) {
if (o instanceof RemoveItemFromListMove) {
RemoveItemFromListMove test = (RemoveItemFromListMove) o;
if (!this.item.equals(test.getBefore())) {
return false;
}
if (this.index != test.index) {
return false;
}
if (this.listKey != test.listKey) {
return false;
}
return true;
}
return false;
}
public FreerailsSerializable getBefore() {
return item;
}
public FreerailsSerializable getAfter() {
return null;
}
public FreerailsPrincipal getPrincipal() {
return principal;
}
}

RemoveTrainMove

Full name: jfreerails.move.RemoveTrainMove

Documentation

/**
* This Move removes a train from the list of trains, and the corresponding
* CargoBundle and Schedule.
*
* @author Luke
*
*/

Source Code

/**
* This Move removes a train from the list of trains, and the corresponding
* CargoBundle and Schedule.
*
* @author Luke
*
*/
public class RemoveTrainMove extends CompositeMove {
private static final long serialVersionUID = 3979265867567544114L;
private RemoveTrainMove(Move[] moves) {
super(moves);
}
public static RemoveTrainMove getInstance(int index, FreerailsPrincipal p,
ReadOnlyWorld world) {
TrainModel train = (TrainModel) world.get(p, KEY.TRAINS, index);
int scheduleId = train.getScheduleID();
ImmutableSchedule schedule = (ImmutableSchedule) world.get(
p, KEY.TRAIN_SCHEDULES, scheduleId);
int cargoBundleId = train.getCargoBundleID();
ImmutableCargoBundle cargoBundle = (ImmutableCargoBundle) world.get(
p, KEY.CARGO_BUNDLES, cargoBundleId);
// TrainPositionOnMap position =
// (TrainPositionOnMap)world.get(KEY.TRAIN_POSITIONS, index, p);
Move removeTrain = new RemoveItemFromListMove(KEY.TRAINS, index, train,
p);
Move removeCargobundle = new RemoveItemFromListMove(KEY.CARGO_BUNDLES,
cargoBundleId, cargoBundle, p);
Move removeSchedule = new RemoveItemFromListMove(KEY.TRAIN_SCHEDULES,
scheduleId, schedule, p);
// Move removePosition = new RemoveItemFromListMove(KEY.TRAIN_POSITIONS,
// index, position, p);
return new RemoveTrainMove(new Move[] { removeTrain, removeCargobundle,
removeSchedule /* , removePosition */
});
}
}

MapUpdateMove

Full name: jfreerails.move.MapUpdateMove

Documentation

/**
* This interface tags Moves that change items on the map and tells the caller
* which tiles have been updated. It is used by the map-view classes to
* determine which tiles need repainting.
*
* @author Luke
*
*/

Source Code

/**
* This interface tags Moves that change items on the map and tells the caller
* which tiles have been updated. It is used by the map-view classes to
* determine which tiles need repainting.
*
* @author Luke
*
*/
public interface MapUpdateMove extends Move {
Rectangle getUpdatedTiles();
}

Methods

AddActiveEntityMove

Full name: jfreerails.move.AddActiveEntityMove

Documentation

/**
* A move that adds an active entity. An active entity is something whose state
* may be continually changing. An example is a train - it is an active entity
* since while it is moving its position is continually changing.
*
* @author Luke
* @see NextActivityMove
*/

Source Code

/**
* A move that adds an active entity. An active entity is something whose state
* may be continually changing. An example is a train - it is an active entity
* since while it is moving its position is continually changing.
*
* @author Luke
* @see NextActivityMove
*/
public class AddActiveEntityMove implements Move {
private static final long serialVersionUID = 8732702087937675013L;
private final Activity activity;
private final FreerailsPrincipal principal;
private final int index;
public AddActiveEntityMove(Activity activity, int index,
FreerailsPrincipal principal) {
this.activity = activity;
this.index = index;
this.principal = principal;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof AddActiveEntityMove))
return false;
final AddActiveEntityMove addActiveEntityMove = (AddActiveEntityMove) o;
if (index != addActiveEntityMove.index)
return false;
if (!activity.equals(addActiveEntityMove.activity))
return false;
if (!principal.equals(addActiveEntityMove.principal))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = activity.hashCode();
result = 29 * result + principal.hashCode();
result = 29 * result + index;
return result;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (index != w.size(principal))
return MoveStatus.moveFailed("index != w.size(listKey, p)");
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int expectedSize = index + 1;
if (expectedSize != w.size(principal))
return MoveStatus
.moveFailed("(index + 1) != w.size(listKey, principal)");
ActivityIterator ai = w.getActivities(principal, index);
if (ai.hasNext())
return MoveStatus
.moveFailed("There should be exactly one activity!");
Activity act = ai.getActivity();
if (!act.equals(activity))
return MoveStatus.moveFailed("Expected " + activity.toString()
+ " but found " + act.toString());
return MoveStatus.MOVE_OK;
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.ok)
w.addActiveEntity(principal, activity);
return ms;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.ok)
w.removeLastActiveEntity(principal);
return ms;
}
}

UndoMove

Full name: jfreerails.move.UndoMove

Documentation

/**
* Undoes the Move passed to its constructor.
*
* @author luke
*/

Source Code

/**
* Undoes the Move passed to its constructor.
*
* @author luke
*/
public class UndoMove implements Move {
private static final long serialVersionUID = 3977582498051929144L;
private Move move2undo;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof UndoMove))
return false;
final UndoMove undoMove = (UndoMove) o;
if (!move2undo.equals(undoMove.move2undo))
return false;
return true;
}
@Override
public int hashCode() {
return move2undo.hashCode();
}
/**
* @param move
* The move that was undone
*/
public UndoMove(Move move) {
if (move instanceof UndoMove) {
throw new IllegalArgumentException();
}
move2undo = move;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
return move2undo.tryUndoMove(w, p);
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
return move2undo.tryDoMove(w, p);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
return move2undo.undoMove(w, p);
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
return move2undo.undoMove(w, p);
}
public Move getUndoneMove() {
return move2undo;
}
}

AddItemToSharedListMove

Full name: jfreerails.move.AddItemToSharedListMove

Documentation

/**
* All moves that add an item to a shared list should extend this class.
*
* @author Luke
*
*/

Source Code

/**
* All moves that add an item to a shared list should extend this class.
*
* @author Luke
*
*/
public class AddItemToSharedListMove implements Move {
private static final long serialVersionUID = 3762256352759722807L;
private final SKEY listKey;
private final int index;
private final FreerailsSerializable item;
public int getIndex() {
return index;
}
@Override
public int hashCode() {
int result;
result = listKey.hashCode();
result = 29 * result + index;
result = 29 * result + (item != null ? item.hashCode() : 0);
return result;
}
public SKEY getKey() {
return listKey;
}
protected AddItemToSharedListMove(SKEY key, int i,
FreerailsSerializable item) {
this.listKey = key;
this.index = i;
this.item = item;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.size(listKey) != index) {
return MoveStatus.moveFailed("Expected size of "
+ listKey.toString() + " list is " + index
+ " but actual size is " + w.size(listKey));
}
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int expectListSize = index + 1;
if (w.size(listKey) != expectListSize) {
return MoveStatus.moveFailed("Expected size of "
+ listKey.toString() + " list is " + expectListSize
+ " but actual size is " + w.size(listKey));
}
return MoveStatus.MOVE_OK;
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.isOk()) {
w.add(listKey, this.item);
}
return ms;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.isOk()) {
w.removeLast(listKey);
}
return ms;
}
@Override
public boolean equals(Object o) {
if (o instanceof AddItemToSharedListMove) {
AddItemToSharedListMove test = (AddItemToSharedListMove) o;
if (!this.item.equals(test.getAfter())) {
return false;
}
if (this.index != test.index) {
return false;
}
if (this.listKey != test.listKey) {
return false;
}
return true;
}
return false;
}
public FreerailsSerializable getBefore() {
return null;
}
public FreerailsSerializable getAfter() {
return item;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer(this.getClass().getName());
sb.append("\nlist=");
sb.append(listKey.toString());
sb.append("\n index =");
sb.append(this.index);
sb.append("\n item =");
sb.append(this.item.toString());
return sb.toString();
}
}

ChangeTrainMove

Full name: jfreerails.move.ChangeTrainMove

Documentation

/**
* This Move can change a train's engine and wagons.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* This Move can change a train's engine and wagons.
*
* @author Luke Lindsay
*
*/
public class ChangeTrainMove extends ChangeItemInListMove {
private static final long serialVersionUID = 3257854272514242873L;
private ChangeTrainMove(int index, FreerailsSerializable before,
FreerailsSerializable after, FreerailsPrincipal p) {
super(KEY.TRAINS, index, before, after, p);
}
public static ChangeTrainMove generateMove(int id, TrainModel before,
int newEngine, ImInts newWagons, FreerailsPrincipal p) {
TrainModel after = before.getNewInstance(newEngine, newWagons);
return new ChangeTrainMove(id, before, after, p);
}
}

AddStationMove

Full name: jfreerails.move.AddStationMove

Documentation

/**
* This {@link CompositeMove}adds a station to the station list and adds a
* cargo bundle (to store the cargo waiting at the station) to the cargo bundle
* list.
*
* @author Luke
*
*/

Source Code

/**
* This {@link CompositeMove}adds a station to the station list and adds a
* cargo bundle (to store the cargo waiting at the station) to the cargo bundle
* list.
*
* @author Luke
*
*/
public class AddStationMove extends CompositeMove {
private static final long serialVersionUID = 3256728398461089080L;
private AddStationMove(Move[] moves) {
super(moves);
}
public StationModel getNewStation() {
AddItemToListMove addStation = (AddItemToListMove) super.getMove(2);
return (StationModel) addStation.getAfter();
}
public static AddStationMove generateMove(ReadOnlyWorld w,
String stationName, ImPoint p,
ChangeTrackPieceMove upgradeTrackMove, FreerailsPrincipal principal) {
int cargoBundleNumber = w.size(principal, KEY.CARGO_BUNDLES);
Move addCargoBundleMove = new AddCargoBundleMove(cargoBundleNumber,
ImmutableCargoBundle.EMPTY_BUNDLE, principal);
int stationNumber = w.size(principal, KEY.STATIONS);
StationModel station = new StationModel(p.x, p.y, stationName, w
.size(SKEY.CARGO_TYPES), cargoBundleNumber);
Move addStation = new AddItemToListMove(KEY.STATIONS, stationNumber,
station, principal);
return new AddStationMove(new Move[] { upgradeTrackMove,
addCargoBundleMove, addStation });
}
public static AddStationMove upgradeStation(
ChangeTrackPieceMove upgradeTrackMove) {
return new AddStationMove(new Move[] { upgradeTrackMove });
}
}

TrainCrashException

Full name: jfreerails.move.TrainCrashException

Documentation

/**
*
* @author mduarte-leon
*/

Source Code

/**
*
* @author mduarte-leon
*/
public class TrainCrashException extends Exception {
private static final long serialVersionUID = 3978710596948342065L;
private int trainA;
private int trainB;
public TrainCrashException() {
}
public TrainCrashException(int aTrain, int bTrain) {
trainA = aTrain;
trainB = bTrain;
}
public int getTrainA() {
return trainA;
}
public int getTrainB() {
return trainB;
}
}

AddPlayerMove

Full name: jfreerails.move.AddPlayerMove

Documentation

/**
* Adds a player to the world.
*
* @author Luke
*/

Source Code

/**
* Adds a player to the world.
*
* @author Luke
*/
public class AddPlayerMove implements Move, ServerMove {
private static final long serialVersionUID = 3977580277537322804L;
private final Player player2add;
private AddPlayerMove(Player p) {
player2add = p;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof AddPlayerMove))
return false;
final AddPlayerMove addPlayerMove = (AddPlayerMove) o;
if (!player2add.equals(addPlayerMove.player2add))
return false;
return true;
}
@Override
public int hashCode() {
return player2add.hashCode();
}
public static AddPlayerMove generateMove(ReadOnlyWorld w, Player player) {
/**
* create a new player with a corresponding Principal
*/
Player player2add = new Player(player.getName(), w.getNumberOfPlayers());
return new AddPlayerMove(player2add);
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (isAlreadyASimilarPlayer(w))
return MoveStatus
.moveFailed("There is already a player with the same name.");
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int numPlayers = w.getNumberOfPlayers();
Player pp = w.getPlayer(numPlayers - 1);
if (pp.equals(player2add)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("The last player is " + pp.getName()
+ "not " + player2add.getName());
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (!ms.ok)
return ms;
int playerId = w.addPlayer(this.player2add);
// Sell the player 2 $500,000 bonds at 5% interest.
FreerailsPrincipal principal = player2add.getPrincipal();
w.addTransaction(principal, BondTransaction.issueBond(5));
//Issue stock
Money initialStockPrice = new Money(5);
Transaction t = StockTransaction.issueStock(playerId, 100000,
initialStockPrice);
w.addTransaction(principal, t);
return ms;
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (!ms.ok)
return ms;
w.removeLastTransaction(player2add.getPrincipal());
w.removeLastTransaction(player2add.getPrincipal());
w.removeLastPlayer();
return ms;
}
private boolean isAlreadyASimilarPlayer(World w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
Player pp = w.getPlayer(i);
if (pp.getName().equalsIgnoreCase(this.player2add.getName())) {
return true;
}
}
return false;
}
}

ServerMove

Full name: jfreerails.move.ServerMove

Documentation

/**
* Indicates a move which can only be submitted by the server.
*
* @author rob
*/

Source Code

/**
* Indicates a move which can only be submitted by the server.
*
* @author rob
*/
public interface ServerMove {
}

Methods

No methods found

UpgradeTrackMove

Full name: jfreerails.move.UpgradeTrackMove

Documentation

/**
* This CompositeMove changes the track type at a point on the map and charges
* the players account for the cost of the change.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* This CompositeMove changes the track type at a point on the map and charges
* the players account for the cost of the change.
*
* @author Luke Lindsay
*
*/
public class UpgradeTrackMove extends CompositeMove implements TrackMove {
private static final long serialVersionUID = 3907215961470875442L;
private UpgradeTrackMove(ChangeTrackPieceMove trackMove) {
super(trackMove);
}
public static UpgradeTrackMove generateMove(TrackPiece before,
TrackPiece after, ImPoint p) {
ChangeTrackPieceMove m = new ChangeTrackPieceMove(before, after, p);
return new UpgradeTrackMove(m);
}
public Rectangle getUpdatedTiles() {
ChangeTrackPieceMove m = (ChangeTrackPieceMove) this.getMove(0);
return m.getUpdatedTiles();
}
}

ChangeTrainScheduleMove

Full name: jfreerails.move.ChangeTrainScheduleMove

Documentation

/**
* This Move changes a train's schedule.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* This Move changes a train's schedule.
*
* @author Luke Lindsay
*
*/
public class ChangeTrainScheduleMove extends ChangeItemInListMove {
private static final long serialVersionUID = 3691043187930052149L;
public ChangeTrainScheduleMove(int id, ImmutableSchedule before,
ImmutableSchedule after, FreerailsPrincipal p) {
super(KEY.TRAIN_SCHEDULES, id, before, after, p);
}
}

ChangeTrackPieceMove

Full name: jfreerails.move.ChangeTrackPieceMove

Documentation

/**
* This Move adds, removes, or upgrades the track on a single tile.
*
* @author Luke
*
*/

Source Code

/**
* This Move adds, removes, or upgrades the track on a single tile.
*
* @author Luke
*
*/
final public class ChangeTrackPieceMove implements TrackMove, MapUpdateMove {
private static final long serialVersionUID = 4120849958418591801L;
final TrackPiece trackPieceBefore;
private final TrackPiece trackPieceAfter;
private final ImPoint location;
public ImPoint getLocation() {
return location;
}
@Override
public int hashCode() {
int result;
result = (trackPieceBefore != null ? trackPieceBefore.hashCode() : 0);
result = 29 * result
+ (trackPieceAfter != null ? trackPieceAfter.hashCode() : 0);
result = 29 * result + location.hashCode();
return result;
}
public TrackPiece getOldTrackPiece() {
return trackPieceBefore;
}
public TrackPiece getNewTrackPiece() {
return trackPieceAfter;
}
public ChangeTrackPieceMove(TrackPiece before, TrackPiece after, ImPoint p) {
trackPieceBefore = before;
trackPieceAfter = after;
location = p;
}
public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
return tryMove(w, this.trackPieceBefore, this.trackPieceAfter);
}
private MoveStatus tryMove(World w, TrackPiece oldTrackPiece,
TrackPiece newTrackPiece) {
// Check that location is on the map.
if (!w.boundsContain(location.x, location.y)) {
return MoveStatus
.moveFailed("Tried to build track outside the map.");
}
// Check that we are not changing another players track if this is not
// allowed.
if (!canConnect2OtherRRsTrack(w)) {
// If either the new or old track piece is null, we are ok.
int oldRuleNumber = oldTrackPiece.getTrackTypeID();
int newRuleNumber = newTrackPiece.getTrackTypeID();
if (NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER != oldRuleNumber
&& NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER != newRuleNumber) {
int oldOwner = oldTrackPiece.getOwnerID();
int newOwner = newTrackPiece.getOwnerID();
if (oldOwner != newOwner) {
return MoveStatus
.moveFailed("Not allowed to connect to other RR");
}
}
}
// Check that the current track piece at this.location is
// the same as this.oldTrackPiece.
TrackPiece currentTrackPieceAtLocation = ((FreerailsTile) w.getTile(
location.x, location.y)).getTrackPiece();
TrackRule expectedTrackRule = oldTrackPiece.getTrackRule();
TrackRule actualTrackRule = currentTrackPieceAtLocation.getTrackRule();
if (!expectedTrackRule.equals(actualTrackRule)) {
return MoveStatus.moveFailed("Expected '"
+ expectedTrackRule.getTypeName() + "' but found '"
+ actualTrackRule.getTypeName() + "' at " + location.x
+ " ," + location.y);
}
if (currentTrackPieceAtLocation.getTrackConfiguration() != oldTrackPiece
.getTrackConfiguration()) {
return MoveStatus
.moveFailed("Unexpected track piece found at location: "
+ location.x + " ," + location.y);
}
// Check that oldTrackPiece is not the same as newTrackPiece
if ((oldTrackPiece.getTrackConfiguration() == newTrackPiece
.getTrackConfiguration())
&& (oldTrackPiece.getTrackRule() == newTrackPiece
.getTrackRule())) {
return MoveStatus.moveFailed("Already track here!");
}
// Check for illegal track configurations.
if (!(oldTrackPiece.getTrackRule().trackPieceIsLegal(
oldTrackPiece.getTrackConfiguration()) && newTrackPiece
.getTrackRule().trackPieceIsLegal(
newTrackPiece.getTrackConfiguration()))) {
return MoveStatus.moveFailed("Illegal track configuration.");
}
// Check for diagonal conflicts.
if (!(noDiagonalTrackConflicts(location, oldTrackPiece
.getTrackGraphicID(), w) && noDiagonalTrackConflicts(location,
newTrackPiece.getTrackGraphicID(), w))) {
return MoveStatus
.moveFailed("Illegal track configuration - diagonal conflict");
}
int terrainType = ((FreerailsTile) w.getTile(location.x, location.y))
.getTerrainTypeID();
TerrainType tt = (TerrainType) w.get(SKEY.TERRAIN_TYPES, terrainType);
if (!newTrackPiece.getTrackRule().canBuildOnThisTerrainType(
tt.getCategory())) {
String thisTrackType = newTrackPiece.getTrackRule().getTypeName();
String terrainCategory = tt.getCategory().toString().toLowerCase();
return MoveStatus.moveFailed("Can't build " + thisTrackType
+ " on " + terrainCategory);
}
// Check 4 overlapping stations.
if (newTrackPiece.getTrackRule().isStation()) {
MoveStatus ms = ChangeTrackPieceMove.check4overlap(w, location,
newTrackPiece);
if (!ms.ok)
return ms;
}
return MoveStatus.MOVE_OK;
}
public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
return tryMove(w, this.trackPieceAfter, this.trackPieceBefore);
}
public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus moveStatus = tryDoMove(w, p);
if (!moveStatus.isOk()) {
return moveStatus;
}
move(w, this.trackPieceBefore, this.trackPieceAfter);
return moveStatus;
}
private void move(World w, TrackPiece oldTrackPiece,
TrackPiece newTrackPiece) {
// FIXME why is oldTrackPiece not used???
FreerailsTile oldTile = (FreerailsTile) w.getTile(location.x,
location.y);
int terrain = oldTile.getTerrainTypeID();
FreerailsTile newTile = FreerailsTile.getInstance(terrain,
newTrackPiece);
w.setTile(location.x, location.y, newTile);
}
public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus moveStatus = tryUndoMove(w, p);
if (!moveStatus.isOk()) {
return moveStatus;
}
move(w, this.trackPieceAfter, this.trackPieceBefore);
return moveStatus;
}
private boolean noDiagonalTrackConflicts(ImPoint point, int trackTemplate,
World w) {
/*
* This method is needs replacing. It only deals with flat track pieces,
* and is rather hard to make sense of. LL
*/
// int trackTemplate = (1 << (3 * (1 + tv.getY()) + (1 + tv.getX())));
int trackTemplateAbove;
int trackTemplateBelow;
int cornersTemplate = TrackConfiguration
.stringTemplate2Int("101000101");
trackTemplate = trackTemplate & cornersTemplate;
Dimension mapSize = new Dimension(w.getMapWidth(), w.getMapHeight());
// Avoid array-out-of-bounds exceptions.
if (point.y > 0) {
FreerailsTile ft = (FreerailsTile)w.getTile(point.x, point.y - 1);
TrackPiece tp = ft.getTrackPiece();
trackTemplateAbove = tp.getTrackGraphicID();
} else {
trackTemplateAbove = 0;
}
if ((point.y + 1) < mapSize.height) {
FreerailsTile ft = (FreerailsTile)w.getTile(point.x, point.y + 1);
TrackPiece tp = ft.getTrackPiece();
trackTemplateBelow = tp.getTrackGraphicID();
} else {
trackTemplateBelow = 0;
}
trackTemplateAbove = trackTemplateAbove >> 6;
trackTemplateBelow = trackTemplateBelow << 6;
trackTemplate = trackTemplate
& (trackTemplateAbove | trackTemplateBelow);
if (trackTemplate != 0) {
return false;
// There is a clash.
}
return true;
// Things are ok.
}
public Rectangle getUpdatedTiles() {
// If we are building or removing a station,
// we need to repaint/remove the station radius
// that appears on the map.
int radius = 1;
TrackRule trackRuleAfter = this.trackPieceAfter.getTrackRule();
if (trackRuleAfter.isStation()) {
radius = Math.max(radius, trackRuleAfter.getStationRadius());
}
TrackRule trackRuleBefore = this.trackPieceBefore.getTrackRule();
if (trackRuleBefore.isStation()) {
radius = Math.max(radius, trackRuleBefore.getStationRadius());
}
// Just to be safe.
radius++;
int x;
int y;
int width;
int height;
x = location.x - radius;
y = location.y - radius;
width = radius * 2 + 1;
height = radius * 2 + 1;
return new Rectangle(x, y, width, height);
}
@Override
public boolean equals(Object o) {
if (o instanceof ChangeTrackPieceMove) {
ChangeTrackPieceMove m = (ChangeTrackPieceMove) o;
boolean fieldPointEqual = this.location.equals(m.location);
boolean fieldoldTrackPieceEqual = this.trackPieceBefore
.equals(m.trackPieceBefore);
boolean fieldnewTrackPieceEqual = this.trackPieceAfter
.equals(m.trackPieceAfter);
if (fieldPointEqual && fieldoldTrackPieceEqual
&& fieldnewTrackPieceEqual) {
return true;
}
return false;
}
return false;
}
protected static boolean canConnect2OtherRRsTrack(ReadOnlyWorld world) {
GameRules rules = (GameRules) world.get(ITEM.GAME_RULES);
return rules.isCanConnect2OtherRRTrack();
}
/**
* This method may be called under 3 possible conditions: (1) when a station
* is getting built, (2) when a station is getting upgraded, (3) when a
* station is getting removed.
*/
protected static MoveStatus check4overlap(World w, ImPoint location,
TrackPiece trackPiece) {
/*
* Fix for 915945 (Stations should not overlap) Check that there is not
* another station whose radius overlaps with the one we are building.
*/
TrackRule thisStationType = trackPiece.getTrackRule();
assert thisStationType.isStation();
for (int player = 0; player < w.getNumberOfPlayers(); player++) {
FreerailsPrincipal principal = w.getPlayer(player).getPrincipal();
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
while (wi.next()) {
StationModel station = (StationModel) wi.getElement();
/*
* Fix for bug 948675 - Can't upgrade station types If locations
* are the same, then we are upgrading a station so it doesn't
* matter if the radii overlap.
*/
if (location.x == station.x && location.y == station.y) {
continue;
}
FreerailsTile tile = (FreerailsTile) w.getTile(station.x,
station.y);
TrackRule otherStationType = tile.getTrackPiece().getTrackRule();
assert otherStationType.isStation();
int sumOfRadii = otherStationType.getStationRadius()
+ thisStationType.getStationRadius();
int sumOfRadiiSquared = sumOfRadii * sumOfRadii;
int xDistance = station.x - location.x;
int yDistance = station.y - location.y;
// Do radii overlap?
boolean xOverlap = sumOfRadiiSquared >= (xDistance * xDistance);
boolean yOverlap = sumOfRadiiSquared >= (yDistance * yDistance);
if (xOverlap && yOverlap) {
String message = "Too close to " + station.getStationName();
return MoveStatus.moveFailed(message);
}
}
}
return MoveStatus.MOVE_OK;
}
}

MoveStatus

Full name: jfreerails.move.MoveStatus

Documentation

/**
* Records the success or failure of an attempt to execute a move.
*
* @author lindsal
*/

Source Code

/**
* Records the success or failure of an attempt to execute a move.
*
* @author lindsal
*/
@Immutable
final public class MoveStatus implements FreerailsSerializable {
private static final long serialVersionUID = 3258129171879309624L;
public static final MoveStatus MOVE_OK = new MoveStatus(true,
"Move accepted");
public final boolean ok;
public final String message;
private final Throwable t;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof MoveStatus))
return false;
final MoveStatus moveStatus = (MoveStatus) o;
if (ok != moveStatus.ok)
return false;
if (message != null ? !message.equals(moveStatus.message)
: moveStatus.message != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = (ok ? 1 : 0);
result = 29 * result + (message != null ? message.hashCode() : 0);
return result;
}
/**
* Avoid creating a duplicate when deserializing.
*/
private Object readResolve() {
if (ok) {
return MOVE_OK;
}
return this;
}
private MoveStatus(boolean ok, String mess) {
if(ok){
t = null;
}else{
t = new Throwable();
t.fillInStackTrace();
}
this.ok = ok;
this.message = mess;
}
public static MoveStatus moveFailed(String reason) {
return new MoveStatus(false, reason);
}
public boolean isOk() {
return ok;
}
public void printStackTrack(){
if(null != t)
t.printStackTrace();
}
@Override
public String toString() {
return message;
}
}

TransferCargoAtStationMove

Full name: jfreerails.move.TransferCargoAtStationMove

Documentation

/**
* This {@link CompositeMove} transfers cargo from a train to a station and
* vice-versa.
*
* @author Luke Lindsay
*
*
*/

Source Code

/**
* This {@link CompositeMove} transfers cargo from a train to a station and
* vice-versa.
*
* @author Luke Lindsay
*
*
*/
public class TransferCargoAtStationMove extends CompositeMove {
private static final long serialVersionUID = 3257291318215456563L;
public static final int CHANGE_ON_TRAIN_INDEX = 1;
public static final int CHANGE_AT_STATION_INDEX = 0;
private final boolean waitingForFullLoad;
private TransferCargoAtStationMove(Move[] moves, boolean waiting) {
super(moves);
waitingForFullLoad = waiting;
}
public static TransferCargoAtStationMove generateMove(
ChangeCargoBundleMove changeAtStation,
ChangeCargoBundleMove changeOnTrain, CompositeMove payment,
boolean waiting) {
return new TransferCargoAtStationMove(new Move[] { changeAtStation,
changeOnTrain, payment }, waiting);
}
public ChangeCargoBundleMove getChangeAtStation() {
return (ChangeCargoBundleMove) super.getMoves().get(
CHANGE_AT_STATION_INDEX);
}
public ChangeCargoBundleMove getChangeOnTrain() {
return (ChangeCargoBundleMove) super.getMoves().get(
CHANGE_ON_TRAIN_INDEX);
}
public Money getRevenue() {
ImList<Move> moves = super.getMoves();
long amount = CHANGE_AT_STATION_INDEX;
for (int i = CHANGE_AT_STATION_INDEX; i < moves.size(); i++) {
if (moves.get(i) instanceof AddTransactionMove) {
AddTransactionMove move = (AddTransactionMove) moves.get(i);
DeliverCargoReceipt receipt = (DeliverCargoReceipt) move
.getTransaction();
amount += receipt.deltaCash().getAmount();
}
}
return new Money(amount);
}
public int getQuantityOfCargo(int cargoType) {
ImList<Move> moves = super.getMoves();
int quantity = CHANGE_AT_STATION_INDEX;
for (int i = CHANGE_AT_STATION_INDEX; i < moves.size(); i++) {
if (moves.get(i) instanceof AddTransactionMove) {
AddTransactionMove move = (AddTransactionMove) moves.get(i);
DeliverCargoReceipt receipt = (DeliverCargoReceipt) move
.getTransaction();
CargoBatch cb = receipt.getCb();
if (cb.getCargoType() == cargoType) {
quantity += receipt.getQuantity();
}
}
}
return quantity;
}
/** The player who is getting paid for the delivery. */
public FreerailsPrincipal getPrincipal() {
ImList<Move> moves = super.getMoves();
for (int i = CHANGE_AT_STATION_INDEX; i < moves.size(); i++) {
if (moves.get(i) instanceof AddTransactionMove) {
AddTransactionMove move = (AddTransactionMove) moves.get(i);
return move.getPrincipal();
}
}
return Player.NOBODY;
}
public TransferCargoAtStationMove(ArrayList<Move> movesArrayList,
boolean waiting) {
super(movesArrayList);
this.waitingForFullLoad = waiting;
}
public boolean isWaitingForFullLoad() {
return waitingForFullLoad;
}
}

ChangeCargoBundleMove

Full name: jfreerails.move.ChangeCargoBundleMove

Documentation

/**
* This {@link Move} changes a cargo bundle (cargo bundles are used to represent
* the cargo carried by trains and the cargo waiting at stations).
*
* @author Luke
*
*/

Source Code

/**
* This {@link Move} changes a cargo bundle (cargo bundles are used to represent
* the cargo carried by trains and the cargo waiting at stations).
*
* @author Luke
*
*/
public class ChangeCargoBundleMove extends ChangeItemInListMove {
private static final long serialVersionUID = 3258126960072143408L;
public ChangeCargoBundleMove(ImmutableCargoBundle before,
ImmutableCargoBundle after, int bundleNumber, FreerailsPrincipal p) {
super(KEY.CARGO_BUNDLES, bundleNumber, before, after, p);
}
}

ListXDDiffsTest

Full name: jfreerails.util.ListXDDiffsTest

Documentation

/**
* Test class for verifying the functionality of List1DDiff, List2DDiff, and List3DDiff.
* This class extends ListXDTest and provides a setup environment to initialize and test
* list difference operations using a sorted map to track differences between lists.
*
* @author [Author Name]
* @see ListXDTest
* @see List1DDiff
* @see List2DDiff
* @see List3DDiff
* @see SortedMap
*/

Source Code

public class ListXDDiffsTest extends ListXDTest {
private SortedMap<ListKey, Object> map;
enum listid{list1, list2, list3}
@Override
protected void setUp() throws Exception {
super.setUp();
map = new TreeMap<ListKey, Object>();
list1d = new List1DDiff<Object>(map, list1d, listid.list1);
list2d = new List2DDiff<Object>(map, list2d, listid.list2);
list3d = new List3DDiff<Object>(map, list3d, listid.list3);
}
}

Methods

UtilsTest

Full name: jfreerails.util.UtilsTest

Documentation

/**
* Test class for the equalsBySerialization method in the Utils class.
* This test verifies that two serializable objects are considered equal if their serialized forms are identical.
* <p>
* The test covers various scenarios including equality of identical objects, self-equality, and inequality between different objects.
* </p>
* @see Utils
* @see Point
*/

Source Code

public class UtilsTest extends TestCase {
public void testEqualsBySerialization() {
Serializable a = new Point(10, 10);
Serializable b = new Point(10, 10);
Serializable c = new Point(30, 10);
assertTrue(Utils.equalsBySerialization(a, b));
assertTrue(Utils.equalsBySerialization(a, a));
assertTrue(Utils.equalsBySerialization(b, b));
assertTrue(Utils.equalsBySerialization(c, c));
assertFalse(Utils.equalsBySerialization(a, c));
}
}

List2DDiffTest

Full name: jfreerails.util.List2DDiffTest

Documentation

/**
* Tests the List2DDiff class, which manages differences in a 2D list structure.
* This class verifies the correctness of various methods including size checks,
* element retrieval, addition, removal, and boundary conditions.
*
* @see jfreerails.util.List2DDiff
*/

Source Code

public class List2DDiffTest extends TestCase {
List2D<Object> underlying;
List2DDiff<Object> diffs;
SortedMap<ListKey, Object> map;
enum listid{test}
@Override
protected void setUp() throws Exception {
underlying = new List2DImpl<Object>(0);
map = new TreeMap<ListKey, Object>();
diffs = new List2DDiff<Object>(map, underlying, listid.test);
}
/*
* Test method for 'jfreerails.util.List2DDiff.sizeD1()'
*/
public void testSizeD1() {
assertEquals(0, diffs.sizeD1());
underlying.addD1();
assertEquals(1, diffs.sizeD1());
}
/*
* Test method for 'jfreerails.util.List2DDiff.sizeD2(int)'
*/
public void testSizeD2() {
underlying.addD1();
assertEquals(1, diffs.sizeD1());
assertEquals(0, diffs.sizeD2(0));
underlying.addD2(0, String.valueOf(1));
assertEquals(1, diffs.sizeD2(0));
}
/*
* Test method for 'jfreerails.util.List2DDiff.get(int, int)'
*/
public void testGetIntInt() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
assertEquals(String.valueOf(1), underlying.get(0, 0));
assertEquals(String.valueOf(1), diffs.get(0, 0));
}
/*
* Test method for 'jfreerails.util.List2DDiff.removeLastD2(int)'
*/
public void testRemoveLastD2() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
Object removed = diffs.removeLastD2(0);
assertEquals(String.valueOf(2), removed);
assertEquals(2, underlying.sizeD2(0));
assertEquals(2, diffs.getUnderlyingSize(0));
assertEquals(1, map.size());
assertEquals(1, diffs.sizeD2(0));
}
/*
* Test method for 'jfreerails.util.List2DDiff.removeLastD1()'
*/
public void testRemoveLastD1() {
underlying.addD1();
underlying.addD1();
assertEquals(2, diffs.sizeD1());
int i = diffs.removeLastD1();
assertEquals(1, i);
assertEquals(1, diffs.sizeD1());
}
/*
* Test method for 'jfreerails.util.List2DDiff.addD1()'
*/
public void testAddD1() {
underlying.addD1();
assertEquals(1, diffs.sizeD1());
assertEquals(1, diffs.getUnderlyingSize());
assertEquals(1, diffs.size());
diffs.addD1();
ListKey sizeKey = new ListKey(EndPoint, listid.test);
assertEquals(2, map.size());
assertTrue(map.containsKey(sizeKey));
assertEquals(new Integer(2), map.get(sizeKey));
assertEquals(2, diffs.sizeD1());
diffs.addD1();
assertEquals(3, diffs.sizeD1());
}
/*
* Test method for 'jfreerails.util.List2DDiff.addD2(int, T)'
*/
public void testAddD2() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
assertEquals(2, diffs.sizeD2(0));
int i = diffs.addD2(0, String.valueOf(3));
assertEquals(2, i);
assertEquals(3, diffs.sizeD2(0));
i = diffs.addD2(0, String.valueOf(4));
assertEquals(3, i);
assertEquals(4, diffs.sizeD2(0));
assertEquals(String.valueOf(3), diffs.get(0, 2));
assertEquals(String.valueOf(4), diffs.get(0, 3));
}
/*
* Test method for 'jfreerails.util.List2DDiff.set(int, int, T)'
*/
public void testSetIntIntT() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
assertEquals(String.valueOf(2), diffs.get(0, 1));
diffs.set(0, 1, String.valueOf(22));
assertEquals(String.valueOf(22), diffs.get(0, 1));
diffs.addD2(0, String.valueOf(3));
assertEquals(String.valueOf(3), diffs.get(0, 2));
diffs.set(0, 2, String.valueOf(33));
assertEquals(String.valueOf(33), diffs.get(0, 2));
}
/*
* Test method for 'jfreerails.util.ListXDDiffs.add(int...)'
*/
public void testAddIntArray() {
assertEquals(0, diffs.sizeD1());
diffs.addDimension();
ListKey sizeKey = new ListKey(EndPoint, listid.test);
assertEquals("There should be two values: EndPoint = 0 and EndPoint[0] = 0", 2, map.size());
assertTrue(map.containsKey(sizeKey));
assertEquals(new Integer(1), map.get(sizeKey));
assertEquals(1, diffs.sizeD1());
assertEquals(0, diffs.sizeD2(0));
diffs.addDimension(0);
assertEquals(1, diffs.sizeD2(0));
}
public void testBoundsOnSet1() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
try {
assertEquals(2, diffs.size(0));
diffs.set(0, 2, String.valueOf(3));
fail();
} catch (Exception e) {
}
}
public void testBoundsOnSet2() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
underlying.addD2(0, String.valueOf(3));
diffs.removeLastD2(0);
diffs.removeLastD2(0);
try {
assertEquals(1, diffs.size(0));
diffs.set(0, 2, String.valueOf(3));
fail();
} catch (Exception e) {
}
}
public void testBoundsOnGet(){
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
underlying.addD2(0, String.valueOf(3));
diffs.removeLastD2(0);
diffs.removeLastD2(0);
try {
assertEquals(1, diffs.size(0));
diffs.get(0, 2);
fail();
} catch (Exception e) {
}
}
public void testReverting2OriginalState1(){
underlying.addD1();
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
diffs.addD1();
assertEquals(3, diffs.sizeD1());
assertEquals(0, diffs.sizeD2(2));
diffs.removeLastD1();
assertEquals(2, diffs.sizeD1());
assertEquals(2, underlying.sizeD1());
assertEquals(0, map.size());
}
public void testReverting2OriginalState2(){
underlying.addD1();
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
diffs.addD1();
diffs.addD2(2, String.valueOf(3));
diffs.addD2(2, String.valueOf(33));
assertEquals(2, diffs.sizeD2(2));
assertEquals(String.valueOf(3), diffs.get(2, 0));
assertEquals(String.valueOf(33), diffs.get(2, 1));
Object removed = diffs.removeLastD2(2);
assertEquals(String.valueOf(33), removed);
removed = diffs.removeLastD2(2);
assertEquals(String.valueOf(3), removed);
assertEquals(0, diffs.sizeD2(2));
assertEquals(3, diffs.sizeD1());
assertEquals(0, diffs.sizeD2(2));
diffs.removeLastD1();
assertEquals(2, diffs.sizeD1());
assertEquals(2, underlying.sizeD1());
assertEquals(0, map.size());
}
public void testAddingElementAlreadyPresent(){
underlying.addD1();
underlying.addD2(0, new Integer(1));
diffs.removeLastD2(0);
diffs.addD2(0, new Integer(1));
assertEquals(0, map.size());
}
public void testAddingNullElement(){
underlying.addD1();
underlying.addD2(0, null);
diffs.removeLastD2(0);
diffs.addD2(0, new Integer(1));
assertEquals(1, map.size());
diffs.removeLastD2(0);
diffs.addD2(0, null);
assertEquals(0, map.size());
diffs.addD2(0, null);
}
public void testSettingNullElement(){
underlying.addD1();
underlying.addD2(0, null);
underlying.addD2(0, new Integer(1));
assertEquals(null, diffs.get(0,0));
diffs.set(0, 0, new Integer(0));
assertEquals(new Integer(0), diffs.get(0,0));
assertEquals(new Integer(1), diffs.get(0,1));
diffs.set(0, 1, null);
assertEquals(null, diffs.get(0,1));
}
}

List3DDiffTest

Full name: jfreerails.util.List3DDiffTest

Documentation

/**
* Tests the List3DDiff class, which manages a 3D list with differences.
* This class contains 12 test methods to verify the functionality of adding,
* removing, and accessing elements in different dimensions (D1, D2, D3),
* as well as checking the size of the list.
*
* @author John Doe
* @see jfreerails.util.List3DDiff
* @see jfreerails.util.List3DImpl
* @see jfreerails.util.ListKey
*/

Source Code

public class List3DDiffTest extends TestCase {
List3DDiff<Object> diffs;
SortedMap<ListKey, Object> map;
List3D<Object> underlying;
enum listid{test}
@Override
protected void setUp() throws Exception {
underlying = new List3DImpl<Object>(0, 0);
map = new TreeMap<ListKey, Object>();
diffs = new List3DDiff<Object>(map, underlying, listid.test);
}
/*
* Test method for 'jfreerails.util.List3DDiff.addD1()'
*/
public void testAddD1() {
diffs.addD1();
assertEquals(1, diffs.sizeD1());
diffs.addD1();
assertEquals(2, diffs.sizeD1());
}
/*
* Test method for 'jfreerails.util.List3DDiff.addD2(int)'
*/
public void testAddD2() {
underlying.addD1();
underlying.addD1();
diffs.addD2(0);
assertEquals(1, diffs.sizeD2(0));
diffs.addD2(0);
assertEquals(2, diffs.sizeD2(0));
diffs.addD2(1);
assertEquals(1, diffs.sizeD2(1));
}
/*
* Test method for 'jfreerails.util.List3DDiff.addD3(int, int, T)'
*/
public void testAddD3() {
underlying.addD1();
underlying.addD1();
underlying.addD2(1);
underlying.addD2(1);
diffs.addD3(1, 0, new Integer(5));
assertEquals(1, diffs.sizeD3(1, 0));
diffs.addD3(1, 1, new Integer(5));
assertEquals(1, diffs.sizeD3(1, 1));
}
/*
* Test method for 'jfreerails.util.List3DDiff.get(int, int, int)'
*/
public void testGetIntIntInt() {
underlying.addD1();
underlying.addD1();
underlying.addD2(1);
underlying.addD2(1);
underlying.addD3(1, 1, new Integer(1));
assertEquals(new Integer(1), diffs.get(1,1,0));
diffs.addD3(1, 1, new Integer(2));
diffs.addD3(1, 1, new Integer(3));
assertEquals(new Integer(2), diffs.get(1,1,1));
assertEquals(new Integer(3), diffs.get(1,1,2));
}
/*
* Test method for 'jfreerails.util.List3DDiff.getUnderlyingSize(int...)'
*/
public void testGetUnderlyingSize() {
assertEquals(-1, diffs.getUnderlyingSize(0,0));
assertEquals(-1, diffs.getUnderlyingSize(0));
assertEquals(0, diffs.getUnderlyingSize());
assertEquals(-1, diffs.getUnderlyingSize(1, 0));
assertEquals(-1, diffs.getUnderlyingSize(0, 1));
underlying.addD1();
underlying.addD1();
assertEquals(2, diffs.getUnderlyingSize());
assertEquals(0, diffs.getUnderlyingSize(1));
assertEquals(0, diffs.getUnderlyingSize(0));
}
/*
* Test method for 'jfreerails.util.List3DDiff.removeLastD1()'
*/
public void testRemoveLastD1() {
underlying.addD1();
underlying.addD1();
assertEquals(2, diffs.sizeD1());
diffs.removeLastD1();
assertEquals(1, diffs.sizeD1());
diffs.removeLastD1();
assertEquals(0, diffs.sizeD1());
try{
diffs.removeLastD1();
fail();
}catch (Exception e) {
}
}
/*
* Test method for 'jfreerails.util.List3DDiff.removeLastD2(int)'
*/
public void testRemoveLastD2() {
underlying.addD1();
underlying.addD2(0);
underlying.addD2(0);
underlying.addD2(0);
assertEquals(3, diffs.sizeD2(0));
diffs.removeLastD2(0);
assertEquals(2, diffs.sizeD2(0));
diffs.removeLastD2(0);
diffs.removeLastD2(0);
assertEquals(0, diffs.sizeD2(0));
try{
diffs.removeLastD2(0);
fail();
}catch (Exception e) {
}
}
/*
* Test method for 'jfreerails.util.List3DDiff.removeLastD3(int, int)'
*/
public void testRemoveLastD3() {
underlying.addD1();
underlying.addD2(0);
underlying.addD3(0,0, new Integer(1));
underlying.addD3(0,0, new Integer(2));
underlying.addD3(0,0, new Integer(3));
assertEquals(3, diffs.sizeD3(0,0));
diffs.removeLastD3(0, 0);
assertEquals(2, diffs.sizeD3(0,0));
diffs.removeLastD3(0, 0);
assertEquals(1, diffs.sizeD3(0,0));
diffs.removeLastD3(0, 0);
assertEquals(0, diffs.sizeD3(0,0));
try{
diffs.removeLastD3(0, 0);
fail();
}catch (Exception e) {
}
}
/*
* Test method for 'jfreerails.util.List3DDiff.set(int, int, int, T)'
*/
public void testSetIntIntIntT() {
underlying.addD1();
underlying.addD2(0);
underlying.addD3(0,0, new Integer(1));
assertEquals(new Integer(1), diffs.get(0, 0, 0));
diffs.addD3(0,0, new Integer(2));
assertEquals(new Integer(2), diffs.get(0, 0, 1));
diffs.set(0,0,0, new Integer(11));
assertEquals(new Integer(11), diffs.get(0, 0, 0));
diffs.set(0,0,1, new Integer(22));
assertEquals(new Integer(22), diffs.get(0, 0, 1));
}
/*
* Test method for 'jfreerails.util.List3DDiff.sizeD1()'
*/
public void testSizeDx() {
assertEquals(0, diffs.sizeD1());
underlying.addD1();
assertEquals(1, diffs.sizeD1());
assertEquals(0, diffs.sizeD2(0));
underlying.addD2(0);
assertEquals(1, diffs.sizeD2(0));
assertEquals(0, diffs.sizeD3(0,0));
underlying.addD3(0,0, new Integer(4));
underlying.addD3(0,0, new Integer(4));
assertEquals(2, diffs.sizeD3(0,0));
}
/*
* Test method for 'jfreerails.util.List3DDiff.uGet(int...)'
*/
public void testUGet() {
underlying.addD1();
underlying.addD2(0);
underlying.addD3(0,0, new Integer(1));
assertEquals(new Integer(1), diffs.uGet(0,0,0));
}
}

ListXDTest

Full name: jfreerails.util.ListXDTest

Documentation

/**
* Test class for verifying the functionality of multi-dimensional list implementations.
* This class contains test cases for adding and removing elements, checking hash codes and equality,
* and validating specific behaviors of 3D lists. It uses JUnit's TestCase framework for assertions.
*
* @author [Author Name]
* @see List1D
* @see List2D
* @see List3D
* @see List1DImpl
* @see List2DImpl
* @see List3DImpl
*/

Source Code

public class ListXDTest extends TestCase {
List1D<Object> list1d;
List2D<Object> list2d;
List3D<Object> list3d;
@Override
protected void setUp() throws Exception {
list1d = new List1DImpl<Object>();
list2d = new List2DImpl<Object>(5);
list3d = new List3DImpl<Object>(3, 2);
}
public void testAdd(){
//Test initial size.
assertEquals(0, list1d.size());
assertEquals(5, list2d.sizeD1());
assertEquals(0, list2d.sizeD2(0));
//Add an object
Integer i = new Integer(4);
assertEquals(0, list1d.add(i));
assertEquals(0, list2d.addD2(2, i));
assertEquals(1, list1d.size());
assertEquals(5, list2d.sizeD1());
assertEquals(1, list2d.sizeD2(2));
assertEquals(0, list2d.sizeD2(0));
}
public void testRemove(){
Integer i = new Integer(4);
list2d.addD2(4, i);
try{
list2d.removeLastD1();
fail();
}catch (Exception e) {
//An exception should be thrown since the list we are trying to remove is not empty.
}
list3d.addD3(2,1,i);
//We now should be able to remove the last
try{
list3d.removeLastD1();
fail();
}catch (Exception e) {
//An exception should be thrown since the list we are trying to remove is not empty.
}
try{
list3d.removeLastD2(3);
fail();
}catch (Exception e) {
//An exception should be thrown since the list we are trying to remove is not empty.
}
}
public void testHashCodeAndEquals(){
Integer i = new Integer(5);
Integer ii = new Integer(53);
//1d
list1d.add(i);
Object copy = Utils.cloneBySerialisation(list1d);
assertEquals(copy, list1d);
assertEquals(copy.hashCode(), list1d.hashCode());
list1d.add(ii);
assertFalse(copy.equals(list1d));
//2d
list2d.addD2(0, i);
copy = Utils.cloneBySerialisation(list2d);
assertEquals(copy, list2d);
assertEquals(copy.hashCode(), list2d.hashCode());
list2d.addD2(0, ii);
assertFalse(copy.equals(list2d));
//3d
list3d.addD3(0, 1, i);
copy = Utils.cloneBySerialisation(list3d);
assertEquals(copy, list3d);
assertEquals(copy.hashCode(), list3d.hashCode());
list3d.addD3(0, 1, ii);
assertFalse(copy.equals(list3d));
}
public void test3DList(){
list3d = new List3DImpl<Object>(0, 0);
//Add a player
int playerId = list3d.addD1();
list3d.addD2(playerId);
list3d.addD2(playerId);
list3d.addD2(playerId);
//Then remove them
while(list3d.sizeD2(playerId)>0){
list3d.removeLastD2(playerId);
}
}
}

List1DDiffsTest

Full name: jfreerails.util.List1DDiffsTest

Documentation

/**
* Test class for the List1DDiff functionality, verifying its behavior
* when tracking differences in a list structure. This class includes
* test cases for value changes, additions, removals, and interactions
* with a SortedMap to manage keyed differences.
*
* @author [Author Name]
* @see List1D
* @see List1DDiff
* @see ListKey
*/

Source Code

public class List1DDiffsTest extends TestCase {
private List1D<Object> list;
private List1DDiff<Object> diffs;
private SortedMap<ListKey, Object> map;
enum test{test}
@Override
protected void setUp() throws Exception {
list = new List1DImpl<Object>();
map = new TreeMap<ListKey, Object>();
diffs = new List1DDiff<Object>(map, list, test.test);
}
public void testChangingValues(){
list.add(String.valueOf(1));
assertEquals(diffs.get(0), String.valueOf(1));
assertEquals(diffs.size(), list.size());
diffs.set(String.valueOf(2), 0);
assertEquals(diffs.get(0), String.valueOf(2));
assertEquals(1, map.size());
diffs.set(String.valueOf(1),0);
assertEquals(0, map.size());
}
public void testAdd(){
Player player0 = new Player("player0", 0);
Player player1 = new Player("player1", 1);
int i = diffs.add(player0);
assertEquals(0, i);
assertEquals(1, diffs.size());
assertEquals(player0, diffs.get(0));
i = diffs.add(player1);
assertEquals(1, i);
assertEquals(2, diffs.size());
assertEquals(player1, diffs.get(1));
}
public void testAddAndRemove(){
list.add(String.valueOf(1));
assertEquals( String.valueOf(1), diffs.get(0));
int i = diffs.add(String.valueOf(2));
assertEquals(1, i);
assertEquals( String.valueOf(1), diffs.get(0));
assertEquals(diffs.get(1), String.valueOf(2));
assertEquals(2, diffs.size());
assertEquals(2, map.size());
Object removed = diffs.removeLast();
assertEquals(String.valueOf(2), removed);
assertEquals(1, diffs.size());
assertEquals(0, map.size());
removed = diffs.removeLast();
assertEquals(String.valueOf(1), removed);
assertEquals(0, diffs.size());
assertEquals(1, map.size());
}
public void testAddAndRemove2(){
list.add(String.valueOf(1));
list.add(String.valueOf(1));
list.add(String.valueOf(1));
diffs.removeLast();
diffs.removeLast();
assertEquals(1, diffs.size());
assertEquals(1, map.size());
diffs.add(String.valueOf(2));
diffs.add(String.valueOf(2));
diffs.add(String.valueOf(2));
diffs.add(String.valueOf(2));
assertEquals(5, diffs.size());
assertEquals("4 elements + end=5", 5, map.size());
assertEquals(String.valueOf(1), diffs.get(0));
assertEquals(String.valueOf(2), diffs.get(1));
assertEquals(String.valueOf(2), diffs.get(2));
assertEquals(String.valueOf(2), diffs.get(3));
assertEquals(String.valueOf(2), diffs.get(3));
diffs.set(String.valueOf(3), 2);
assertEquals(5, diffs.size());
assertEquals(5, map.size());
assertEquals(String.valueOf(3), diffs.get(2));
diffs.set(String.valueOf(4), 4);
assertEquals(String.valueOf(4), diffs.get(4));
diffs.removeLast();
diffs.removeLast();
diffs.removeLast();
diffs.removeLast();
assertEquals(1, diffs.size());
assertEquals("fork=1", 1, map.size());
}
public void testSortedMap(){
ListKey elementKey1 = new ListKey(ListKey.Type.Element, test.test, 0);
ListKey elementKey2 = new ListKey(ListKey.Type.Element, test.test, 1);
ListKey elementKey3 = new ListKey(ListKey.Type.Element, test.test, 0);
map.put(elementKey1, String.valueOf(1));
assertFalse(map.containsKey(elementKey2));
assertTrue(map.containsKey(elementKey1));
assertTrue(map.containsKey(elementKey3));
}
}

List2DDiff

Full name: jfreerails.util.List2DDiff

Documentation

/**
* Represents a two-dimensional list that tracks differences (diffs) between its current state and an underlying list.
* This class provides methods to manipulate and inspect the list while delegating operations to the superclass for diff tracking.
* It wraps a {@link List2D} instance and exposes its structure through diff-aware methods.
*
* @author Generated Documentation
* @see ListXDDiffs
* @see List2D
* @see Lists
*/

Source Code

public class List2DDiff<T> extends ListXDDiffs<T> implements List2D<T> {
private final List2D<T> underlyingList;
public List2DDiff(SortedMap<ListKey, Object> diffs, List2D<T> list,
Enum listID) {
super(diffs, listID);
underlyingList = list;
}
private static final long serialVersionUID = 4323585276281406244L;
public int sizeD1() {
return super.size();
}
public int sizeD2(int d1) {
return super.size(d1);
}
public T get(int d1, int d2) {
return super.get(d1, d2);
}
public T removeLastD2(int d1) {
return super.removeLast(d1);
}
public int removeLastD1() {
return super.removeLastList();
}
public int addD1() {
return super.addDimension();
}
public int addD2(int d1, T element) {
return super.addElement(element, d1);
}
public void set(int d1, int d2, T element) {
super.set(element, d1, d2);
}
@Override
Object getUnderlyingList() {
return underlyingList;
}
@Override
T uGet(int... i) {
if (i.length != 2)
throw new IllegalArgumentException(String.valueOf(i.length));
return underlyingList.get(i[0], i[1]);
}
@Override
int getUnderlyingSize(int... dim) {
if(dim.length == 0)
return underlyingList.sizeD1();
if(dim.length == 1){
if (underlyingList.sizeD1() <= dim[0])
return -1;
return underlyingList.sizeD2(dim[0]);
}
throw new IllegalArgumentException(String.valueOf(dim.length));
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof List2D))
return false;
return Lists.equals(this, (List2D)obj);
}
@Override
public int hashCode() {
return sizeD1();
}
}

List1D

Full name: jfreerails.util.List1D

Documentation

/**
* Represents a one-dimensional list of elements of type T.
* This interface provides methods to manage the list, including adding, removing,
* accessing, and modifying elements.
*
* @since 1.0
* @see java.util.List
*/

Source Code

public interface List1D<T> extends Serializable {
int size();
T get(int i);
T removeLast();
int add(T element);
void set(int i, T element);
}

Utils

Full name: jfreerails.util.Utils

Documentation

/**
* A bunch of static methods.
*
* @author Luke
*
*/

Source Code

/**
* A bunch of static methods.
*
* @author Luke
*
*/
strictfp public class Utils {
public static boolean equalsBySerialization(Serializable a, Serializable b) {
byte[] bytesA = write2ByteArray(a);
byte[] bytesB = write2ByteArray(b);
if (bytesA.length != bytesB.length)
return false;
for (int i = 0; i < bytesA.length; i++) {
if (bytesA[i] != bytesB[i])
return false;
}
return true;
}
/** Used when debugging. */
public static void write(Serializable m, String fileName) {
try {
File f = new File(fileName);
OutputStream out = new FileOutputStream(f);
ObjectOutputStream objectOut = new ObjectOutputStream(out);
objectOut.writeObject(m);
objectOut.flush();
objectOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Serializable cloneBySerialisation(Serializable m) {
try {
byte[] bytes = write2ByteArray(m);
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
ObjectInputStream objectIn = new ObjectInputStream(in);
Serializable o;
o = (Serializable) objectIn.readObject();
return o;
} catch (ClassNotFoundException e) {
// Should never happen.
throw new IllegalStateException();
} catch (IOException e) {
// Should never happen.
e.printStackTrace();
throw new IllegalStateException();
}
}
private static byte[] write2ByteArray(Serializable m) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ObjectOutputStream objectOut = new ObjectOutputStream(out);
objectOut.writeObject(m);
objectOut.flush();
} catch (IOException e) {
// Should never happen.
e.printStackTrace();
throw new IllegalStateException();
}
byte[] bytes = out.toByteArray();
return bytes;
}
public static String capitalizeEveryWord(String str) {
StringBuffer result = new StringBuffer();
StringTokenizer tok = new StringTokenizer(str);
while (tok.hasMoreTokens()) {
String token = tok.nextToken().toLowerCase();
result.append(Character.toUpperCase(token.charAt(0))
+ token.substring(1) + " ");
}
return result.toString().trim();
}
public static String findConstantFieldName(Object o) {
Field[] fields = o.getClass().getFields();
for (int i = 0; i < fields.length; i++) {
int modifiers = fields[i].getModifiers();
try {
if (Modifier.isStatic(modifiers)
&& Modifier.isPublic(modifiers)) {
Object o2 = fields[i].get(null);
if (o2.equals(o)) {
return fields[i].getName();
}
}
} catch (IllegalAccessException e) {
throw new IllegalStateException();
}
}
return null;
}
/**
* Returns the largest solution of the quadratic equation ax<sup><font
* size="-1">2</font></sup> + bx + c = 0.
*
* @throws IllegalArgumentException
* if <code>a == 0</code>
* @throws IllegalArgumentException
* if <code>(b * b - 4 * a * c) < 0</code>
*/
public static double solveQuadratic(double a, double b, double c)
throws IllegalArgumentException {
if (a == 0) {
throw new IllegalArgumentException("a == 0");
}
double disc = b * b - 4 * a * c;
if (disc < 0)
throw new IllegalArgumentException("(b * b - 4 * a * c) < 0");
return (-b + StrictMath.sqrt(disc)) / (2 * a);
}
public static int hypotenuse(int a, int b) {
double d = Math.hypot(a, b);
return (int) Math.round(d);
}
/**
* Returns true if the objects are equal or both null, otherwise returns
* false. Does not throw null pointer exceptions when either of the objects
* is null.
*/
public static boolean equal(Object a, Object b) {
if (null == a || null == b) {
return null == a && null == b;
}
return a.equals(b);
}
}

CompressedInputStream

Full name: jfreerails.util.CompressedInputStream

Documentation

/**
* A FilterInputStream for reading compressed data from a network connection.
*
* @author Patrice Espie Licensing: LGPL
* @see CompressedOutputStream
*/

Source Code

/**
* A FilterInputStream for reading compressed data from a network connection.
*
* @author Patrice Espie Licensing: LGPL
* @see CompressedOutputStream
*/
public class CompressedInputStream extends FilterInputStream {
public CompressedInputStream(InputStream in) {
super(in);
buffer = new byte[0x7d000];
compBuffer = new byte[(int) (buffer.length * 1.2D)];
readIndex = 0;
maxReadIndex = 0;
inflater = new Inflater();
}
@Override
public boolean markSupported() {
return false;
}
@Override
public int available() throws IOException {
if (maxReadIndex - readIndex == 0 && super.in.available() > 0
&& !readNextBuffer()) {
return -1;
}
return maxReadIndex - readIndex;
}
@Override
public int read() throws IOException {
if (maxReadIndex - readIndex == 0 && !readNextBuffer()) {
return -1;
}
byte b = buffer[readIndex++];
if (b < 0) {
return 256 + b;
}
return b;
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (maxReadIndex - readIndex == 0 && !readNextBuffer()) {
return -1;
}
int read = 0;
for (int i = 0; i < len && available() > 0;) {
b[off + i] = (byte) read();
i++;
read++;
}
return read;
}
private boolean readNextBuffer() throws IOException {
byte compressionFlag = -1;
compressionFlag = (byte) super.in.read();
if (compressionFlag == -1) {
return false;
}
maxReadIndex = super.in.read() & 0xff;
maxReadIndex = maxReadIndex << 8 | super.in.read() & 0xff;
maxReadIndex = maxReadIndex << 8 | super.in.read() & 0xff;
maxReadIndex = maxReadIndex << 8 | super.in.read() & 0xff;
if (buffer.length < maxReadIndex) {
buffer = new byte[maxReadIndex + 40960];
}
if (compressionFlag == 1) {
int compSize = super.in.read() & 0xff;
compSize = compSize << 8 | super.in.read() & 0xff;
compSize = compSize << 8 | super.in.read() & 0xff;
compSize = compSize << 8 | super.in.read() & 0xff;
if (compBuffer.length < compSize) {
compBuffer = new byte[compSize + 40960];
}
for (int read = 0; read < compSize; read += super.in.read(
compBuffer, read, compSize - read)) {
}
inflater.reset();
inflater.setInput(compBuffer, 0, compSize);
try {
inflater.inflate(buffer);
} catch (DataFormatException ex) {
throw new IOException("Data format exception");
}
} else if (compressionFlag == 0) {
for (int read = 0; read < maxReadIndex; read += super.in.read(
buffer, read, maxReadIndex - read)) {
}
}
readIndex = 0;
return true;
}
private byte[] buffer;
private byte[] compBuffer;
private int readIndex;
private int maxReadIndex;
private Inflater inflater;
}

FreerailsProgressMonitor

Full name: jfreerails.util.FreerailsProgressMonitor

Documentation

/**
* This interface defines callbacks that can be used to let the user know how a
* slow task is progressing.
*
* @author Luke Lindsay
*/

Source Code

/**
* This interface defines callbacks that can be used to let the user know how a
* slow task is progressing.
*
* @author Luke Lindsay
*/
public interface FreerailsProgressMonitor {
public static final FreerailsProgressMonitor NULL_INSTANCE = new FreerailsProgressMonitor() {
public void setValue(int i) {
}
public void nextStep(int max) {
}
public void finished() {
}
};
void setValue(int i);
void nextStep(int max);
void finished();
}

ListXDDiffs

Full name: jfreerails.util.ListXDDiffs

Documentation

/**
* Manages and tracks differences in a multi-dimensional list structure, providing methods to add, remove, and retrieve elements while maintaining diff information for comparison or versioning purposes.
* This abstract class serves as a base for implementing list diff tracking mechanisms, encapsulating operations to modify the list and persist changes in a {@link SortedMap} of {@link ListKey} entries.
*
* @author YourName
* @since 1.0
*
* @see ListKey
* @see SortedMap
* @see Serializable
*/

Source Code

public abstract class ListXDDiffs<T> implements Serializable {
private static final long serialVersionUID = 127789045793369316L;
static int[] add2Array(int[] dim, int last) {
int[] array = new int[dim.length + 1];
for (int i = 0; i < dim.length; i++) {
array[i] = dim[i];
}
array[array.length - 1] = last;
return array;
}
static int[] removeFromArray(int[] dim) {
int[] array = new int[dim.length - 1];
for (int i = 0; i < dim.length - 1; i++) {
array[i] = dim[i];
}
return array;
}
private final SortedMap<ListKey, Object> diffs;
private final Enum listID;
public ListXDDiffs(SortedMap<ListKey, Object> diffs, Enum listID) {
this.diffs = diffs;
this.listID = listID;
}
public int addDimension(int... dim) {
int i = size(dim);
ListKey sizeKeyA = new ListKey(ListKey.Type.EndPoint, listID, dim);
int[] subArray = add2Array(dim, i);
ListKey sizeKeyB = new ListKey(ListKey.Type.EndPoint, listID, subArray);
diffs.put(sizeKeyA, new Integer(i + 1));
diffs.put(sizeKeyB, new Integer(0));
return i;
}
public int addElement(T element, int... dim) {
int sizeBefore = size(dim);
int[] index = add2Array(dim, sizeBefore);
setElementDiff: {
if (getUnderlyingSize(dim) > sizeBefore) {
T uElement = uGet(index);
if (Utils.equal(uElement, element)) {
// We are reading an element that was removed, in which
// case we don't store a diff.
break setElementDiff;
}
}
ListKey elementKey = new ListKey(ListKey.Type.Element, listID,
index);
diffs.put(elementKey, element);
}
setSize(sizeBefore + 1, dim);
return sizeBefore;
}
@SuppressWarnings("unchecked")
public T get(int... i) {
checkBounds(i);
ListKey elementKey = new ListKey(ListKey.Type.Element, listID, i);
if (diffs.containsKey(elementKey)) {
return (T) diffs.get(elementKey);
}
return uGet(i);
}
abstract Object getUnderlyingList();
/**
* Returns the size of the underlying list at the specified dimension or -1
* if the underlying list does not have the specified dimension.
*/
abstract int getUnderlyingSize(int... dim);
@SuppressWarnings("unchecked")
public T removeLast(int... dim) {
T toRemove;
int last = size(dim) - 1;
int[] array = add2Array(dim, last);
ListKey elementKey = new ListKey(ListKey.Type.Element, listID, array);
if (diffs.containsKey(elementKey)) {
toRemove = (T) diffs.remove(elementKey);
} else {
toRemove = uGet(array);
}
setSize(last, dim);
return toRemove;
}
int removeLastList(int... dim) {
int last = size(dim) - 1;
// Check that the list we are removing is empty.
int[] array = add2Array(dim, last);
if (0 != size(array))
throw new IllegalStateException();
ListKey sizeKeyB = new ListKey(ListKey.Type.EndPoint, listID, array);
diffs.remove(sizeKeyB);
setSize(last, dim);
return last;
}
public void set(T element, int... i) {
// Check bounds..
checkBounds(i);
int last = i[i.length - 1];
int[] dim = checkBounds(i);
ListKey elementKey = new ListKey(ListKey.Type.Element, listID, i);
boolean b = getUnderlyingSize(dim) > last;
if (b && Utils.equal(uGet(i), element)) {
if (diffs.containsKey(elementKey))
diffs.remove(elementKey);
} else {
diffs.put(elementKey, element);
}
}
private int[] checkBounds(int... i) {
int[] dim = removeFromArray(i);
int last = i[i.length - 1];
if (last >= size(dim))
throw new IndexOutOfBoundsException(String.valueOf(last));
return dim;
}
private void setSize(int size, int... dim) {
ListKey sizeKey = new ListKey(ListKey.Type.EndPoint, listID, dim);
if (getUnderlyingSize(dim) == size) {
diffs.remove(sizeKey);
} else {
diffs.put(sizeKey, new Integer(size));
}
}
public int size(int... i) {
ListKey sizeKey = new ListKey(ListKey.Type.EndPoint, listID, i);
if (diffs.containsKey(sizeKey)) {
Integer size = (Integer) diffs.get(sizeKey);
return size.intValue();
}
return getUnderlyingSize(i);
}
abstract T uGet(int... i);
// abstract int uSize(int... i);
}

List3DImpl

Full name: jfreerails.util.List3DImpl

Documentation

/**
* A 3D list implementation that manages elements in three dimensions.
* This class provides methods to add, remove, and access elements in a 3D structure.
*
* @author Your Name
* @since 1.0
* @see List3D
*/

Source Code

public class List3DImpl<T> implements List3D<T> {
private static final long serialVersionUID = 1353309875727204066L;
private ArrayList<ArrayList<ArrayList<T>>> elementData= new ArrayList<ArrayList<ArrayList<T>>>();
public List3DImpl(int d1, int d2){
for (int i = 0; i < d1; i++) {
ArrayList<ArrayList<T>> dim2 = new ArrayList<ArrayList<T>>();
elementData.add(dim2);
for (int j = 0; j < d2; j++) {
dim2.add(new ArrayList<T>() );
}
}
}
public int sizeD1() {
return elementData.size();
}
public int sizeD2(int d1) {
return elementData.get(d1).size();
}
public int sizeD3(int d1, int d2) {
return elementData.get(d1).get(d2).size();
}
public T get(int d1, int d2, int d3) {
return elementData.get(d1).get(d2).get(d3);
}
public T removeLastD3(int d1, int d2) {
ArrayList<T> dim3 = elementData.get(d1).get(d2);
int last = dim3.size()-1;
T element = dim3.get(last);
dim3.remove(last);
return element;
}
public void removeLastD1() {
int last = elementData.size()-1;
if(elementData.get(last).size() > 0)
throw new IllegalStateException(String.valueOf(last));
elementData.remove(last);
}
public void removeLastD2(int d1) {
ArrayList<ArrayList<T>> dim2 = elementData.get(d1);
int last = dim2.size()-1;
ArrayList<T> dim3 = dim2.get(last);
if(dim3.size() > 0)
throw new IllegalStateException(String.valueOf(d1));
dim2.remove(last);
}
public int addD1() {
ArrayList<ArrayList<T>> dim2 = new ArrayList<ArrayList<T>>();
elementData.add(dim2);
return elementData.size() -1;
}
public int addD2(int d1) {
ArrayList<ArrayList<T>> dim2 = elementData.get(d1);
dim2.add(new ArrayList<T>() );
return dim2.size()-1;
}
public int addD3(int d1, int d2, T element) {
ArrayList<T> dim3 = elementData.get(d1).get(d2);
dim3.add(element);
return dim3.size()-1;
}
public void set(int d1, int d2, int d3, T element) {
ArrayList<T> dim3 = elementData.get(d1).get(d2);
dim3.set(d3, element);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof List3D))
return false;
return Lists.equals(this, (List3D)obj);
}
@Override
public int hashCode() {
return sizeD1();
}
public List<T> get(int d1, int d2) {
return elementData.get(d1).get(d2);
}
}

LRUCache

Full name: jfreerails.util.LRUCache

Documentation

/**
* An LRU cache, based on <code>LinkedHashMap</code>.<br>
* This cache has a fixed maximum number of elements (<code>cacheSize</code>).
* If the cache is full and another entry is added, the LRU (least recently
* used) entry is dropped.
* <p>
* This class is thread-safe. All methods of this class are synchronized.<br>
* Author: Christian d'Heureuse (<a
* href="http://www.source-code.biz">www.source-code.biz</a>)<br>
* License: <a href="http://www.gnu.org/licenses/lgpl.html">LGPL</a>.
*/

Source Code

/**
* An LRU cache, based on <code>LinkedHashMap</code>.<br>
* This cache has a fixed maximum number of elements (<code>cacheSize</code>).
* If the cache is full and another entry is added, the LRU (least recently
* used) entry is dropped.
* <p>
* This class is thread-safe. All methods of this class are synchronized.<br>
* Author: Christian d'Heureuse (<a
* href="http://www.source-code.biz">www.source-code.biz</a>)<br>
* License: <a href="http://www.gnu.org/licenses/lgpl.html">LGPL</a>.
*/
public class LRUCache<K, V> {
private static final float hashTableLoadFactor = 0.75f;
private LinkedHashMap<K, V> map;
private int cacheSize;
/**
* Creates a new LRU cache.
*
* @param cacheSize
* the maximum number of entries that will be kept in this cache.
*/
public LRUCache(int cacheSize) {
this.cacheSize = cacheSize;
int hashTableCapacity = (int) Math
.ceil(cacheSize / hashTableLoadFactor) + 1;
map = new LinkedHashMap<K, V>(hashTableCapacity, hashTableLoadFactor,
true) {
// (an anonymous inner class)
private static final long serialVersionUID = 1;
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > LRUCache.this.cacheSize;
}
};
}
/**
* Retrieves an entry from the cache.<br>
* The retrieved entry becomes the MRU (most recently used) entry.
*
* @param key
* the key whose associated value is to be returned.
* @return the value associated to this key, or null if no value with this
* key exists in the cache.
*/
public synchronized V get(K key) {
return map.get(key);
}
/**
* Adds an entry to this cache. If the cache is full, the LRU (least
* recently used) entry is dropped.
*
* @param key
* the key with which the specified value is to be associated.
* @param value
* a value to be associated with the specified key.
*/
public synchronized void put(K key, V value) {
map.put(key, value);
}
/**
* Clears the cache.
*/
public synchronized void clear() {
map.clear();
}
/**
* Returns the number of used entries in the cache.
*
* @return the number of entries currently in the cache.
*/
public synchronized int usedEntries() {
return map.size();
}
/**
* Returns a <code>Collection</code> that contains a copy of all cache
* entries.
*
* @return a <code>Collection</code> with a copy of the cache content.
*/
public synchronized Collection<Map.Entry<K, V>> getAll() {
return new ArrayList<Map.Entry<K, V>>(map.entrySet());
}
} // end class LRUCache

FlowRateInputStream

Full name: jfreerails.util.FlowRateInputStream

Documentation

/**
* A FilterInputStream that measures flow rate.
*
* @author Patrice Espie Licensing: LGPL
*/

Source Code

/**
* A FilterInputStream that measures flow rate.
*
* @author Patrice Espie Licensing: LGPL
*/
public class FlowRateInputStream extends FilterInputStream implements Runnable {
private static final Logger logger = Logger
.getLogger(FlowRateInputStream.class.getName());
public FlowRateInputStream(InputStream in, String streamName) {
this(in, streamName, 60, 1000);
}
public FlowRateInputStream(InputStream in, String streamName,
int measureDuration, int measureInterval) {
super(in);
byteReceivedCumul = 0L;
totalByteReceived = 0L;
previousTotalByteReceived = 0L;
openTimeMillis = System.currentTimeMillis();
nextFree = 0;
nbUsed = 0;
running = false;
closeRequested = false;
byteReceived = new long[measureDuration];
this.measureInterval = measureInterval;
this.streamName = streamName;
if (this.measureInterval == 0) {
showTrace = false;
this.measureInterval = 1000L;
} else {
showTrace = true;
}
(new Thread(this)).start();
}
public FlowRateInputStream(InputStream in) {
this(in, "FlowRateInputStream", 60, 1000);
}
@Override
public void close() throws IOException {
closeRequested = true;
super.close();
do {
try {
Thread.currentThread();
Thread.sleep(50L);
} catch (InterruptedException interruptedexception) {
}
} while (running);
logger.info(String.valueOf(String.valueOf((new StringBuffer("Stream "))
.append(streamName).append(": Open duration = ").append(
(System.currentTimeMillis() - openTimeMillis) / 1000D)
.append(", Byte received = ").append(totalByteReceived).append(
" (").append((int) (totalByteReceived / 1024D)).append(
" Ko), overall flow rate = ").append(overallRate())
.append(" Ko/s"))));
}
@Override
public int read() throws IOException {
int r = super.in.read();
totalByteReceived += r;
return r;
}
@Override
public int read(byte[] b) throws IOException {
int r = super.in.read(b);
totalByteReceived += r;
return r;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int r = super.in.read(b, off, len);
totalByteReceived += r;
return r;
}
public int currentRate() {
return (int) (byteReceivedCumul / 1024D / (nbUsed * (measureInterval / 1000D)));
}
public String currentRateString() {
double d = (byteReceivedCumul / 1024D / (nbUsed * (measureInterval / 1000D)));
return decimalFormat.format(d);
}
public int overallRate() {
return (int) (totalByteReceived / 1024D / ((System.currentTimeMillis() - openTimeMillis) / 1000D));
}
public void run() {
if (running || measureInterval == 0x7fffffffffffffffL) {
return;
}
running = true;
try {
do {
try {
Thread.currentThread();
Thread.sleep(measureInterval);
} catch (InterruptedException interruptedexception) {
}
if (!closeRequested) {
long totalByteReceivedCopy = totalByteReceived;
long byteSentThisTime = totalByteReceivedCopy
- previousTotalByteReceived;
previousTotalByteReceived = totalByteReceivedCopy;
byteReceivedCumul -= byteReceived[nextFree];
byteReceived[nextFree] = byteSentThisTime;
byteReceivedCumul += byteSentThisTime;
nextFree = (nextFree + 1) % byteReceived.length;
nbUsed = Math.min(byteReceived.length, nbUsed + 1);
if (showTrace) {
logger
.info(String
.valueOf(String
.valueOf((new StringBuffer(
"Stream "))
.append(streamName)
.append(
": Open duration = ")
.append(
(System
.currentTimeMillis() - openTimeMillis) / 1000D)
.append(
", Byte sent = ")
.append(
totalByteReceived)
.append(" (")
.append(
(int) (totalByteReceived / 1024D))
.append(
" Ko), current flow rate = ")
.append(
currentRateString())
.append(" Ko/s"))));
}
}
} while (!closeRequested);
} finally {
running = false;
}
}
private long[] byteReceived;
private long byteReceivedCumul;
private long totalByteReceived;
private long previousTotalByteReceived;
private long openTimeMillis;
private long measureInterval;
private int nextFree;
private int nbUsed;
private boolean running;
private boolean closeRequested;
private String streamName;
private boolean showTrace;
private DecimalFormat decimalFormat = new DecimalFormat("0.00");
}

GrowableBase

Full name: jfreerails.util.GrowableBase

Documentation

/**
* Base class for various types of collections based on type-specific growable
* arrays. The underlying array used for storage of items doubles in size each
* time more space is required, up to an optional maximum growth increment
* specified by the user.
*
* @author Dennis M. Sosnoski
* @version 1.0
*/

Source Code

/**
* Base class for various types of collections based on type-specific growable
* arrays. The underlying array used for storage of items doubles in size each
* time more space is required, up to an optional maximum growth increment
* specified by the user.
*
* @author Dennis M. Sosnoski
* @version 1.0
*/
public abstract class GrowableBase implements Serializable {
/** Default initial array size. */
public static final int DEFAULT_SIZE = 8;
/** Size of the current array. */
protected int countLimit;
/** Maximum size increment for growing array. */
protected int maximumGrowth;
/**
* Constructor with full specification.
*
* @param size
* number of elements in initial array
* @param growth
* maximum size increment for growing array
* @param type
* array element type
*/
public GrowableBase(int size, int growth, Class type) {
Object array = Array.newInstance(type, size);
countLimit = size;
maximumGrowth = growth;
setArray(array);
}
/**
* Constructor with partial specification.
*
* @param size
* number of elements initially allowed in array
* @param type
* array element type
*/
public GrowableBase(int size, Class type) {
this(size, Integer.MAX_VALUE, type);
}
/**
* Copy (clone) constructor.
*
* @param base
* instance being copied
*/
public GrowableBase(GrowableBase base) {
this(base.countLimit, base.maximumGrowth, base.getArray().getClass()
.getComponentType());
}
/**
* Get the backing array. This method is used by the type-agnostic base
* class code to access the array used for type-specific storage by the
* child class.
*
* @return backing array object
*/
protected abstract Object getArray();
/**
* Set the backing array. This method is used by the type-agnostic base
* class code to set the array used for type-specific storage by the child
* class.
*
*/
protected abstract void setArray(Object array);
/**
* Copy data after array resize. This default implementation just copies the
* entire contents of the old array to the start of the new array. It should
* be overridden in cases where data needs to be rearranged in the array
* after a resize.
*
* @param base
* original array containing data
* @param grown
* resized array for data
*/
protected void resizeCopy(Object base, Object grown) {
System.arraycopy(base, 0, grown, 0, Array.getLength(base));
}
/**
* Discards values for a range of indices in the array. Checks if the values
* stored in the array are object references, and if so clears them. If the
* values are primitives, this method does nothing.
*
* @param from
* index of first value to be discarded
* @param to
* index past last value to be discarded
*/
protected void discardValues(int from, int to) {
Object values = getArray();
if (!values.getClass().getComponentType().isPrimitive()) {
Object[] objects = (Object[]) values;
for (int i = from; i < to; i++) {
objects[i] = null;
}
}
}
/**
* Increase the size of the array to at least a specified size. The array
* will normally be at least doubled in size, but if a maximum size
* increment was specified in the constructor and the value is less than the
* current size of the array, the maximum increment will be used instead. If
* the requested size requires more than the default growth, the requested
* size overrides the normal growth and determines the size of the
* replacement array.
*
* @param required
* new minimum size required
*/
protected void growArray(int required) {
Object base = getArray();
int size = Math.max(required, countLimit
+ Math.min(countLimit, maximumGrowth));
Class type = base.getClass().getComponentType();
Object grown = Array.newInstance(type, size);
resizeCopy(base, grown);
countLimit = size;
setArray(grown);
}
/**
* Ensure that the array has the capacity for at least the specified number
* of values.
*
* @param min
* minimum capacity to be guaranteed
*/
public final void ensureCapacity(int min) {
if (min > countLimit) {
growArray(min);
}
}
/**
* Constructs and returns a simple array containing the same data as held in
* a portion of this growable array.
*
* @param type
* element type for constructed array
* @param offset
* start offset in array
* @param length
* number of characters to use
* @return array containing a copy of the data
*/
protected Object buildArray(Class type, int offset, int length) {
Object copy = Array.newInstance(type, length);
System.arraycopy(getArray(), offset, copy, 0, length);
return copy;
}
}

Lists

Full name: jfreerails.util.Lists

Documentation

/**
* Utility class providing methods to compare lists of different dimensions for equality.
* <p>
* This class contains static methods to check if two lists (1D, 2D, or 3D) are equal by
* recursively comparing their elements using the Utils.equal method.
* </p>
* @see List1D
* @see List2D
* @see List3, List3D
* @see Utils
*/

Source Code

public class Lists {
@SuppressWarnings("unchecked")
public static boolean equals(List1D a, List1D b) {
if (a.size() != b.size())
return false;
for (int i = 0; i < a.size(); i++) {
if (!Utils.equal(a.get(i), b.get(i)))
return false;
}
return true;
}
@SuppressWarnings("unchecked")
public static boolean equals(List2D a, List2D b) {
if (a.sizeD1() != b.sizeD1())
return false;
for (int d1 = 0; d1 < a.sizeD1(); d1++) {
if (a.sizeD2(d1) != b.sizeD2(d1))
return false;
for (int d2 = 0; d2 < a.sizeD2(d1); d2++) {
if (!Utils.equal(a.get(d1, d2), b.get(d1, d2)))
return false;
}
}
return true;
}
@SuppressWarnings("unchecked")
public static boolean equals(List3D a, List3D b) {
if (a.sizeD1() != b.sizeD1())
return false;
for (int d1 = 0; d1 < a.sizeD1(); d1++) {
if (a.sizeD2(d1) != b.sizeD2(d1))
return false;
for (int d2 = 0; d2 < a.sizeD2(d1); d2++) {
if (a.sizeD3(d1, d2) != b.sizeD3(d1, d2))
return false;
for (int d3 = 0; d3 < a.sizeD3(d1, d2); d3++) {
if (!Utils.equal(a.get(d1, d2, d3), b.get(d1, d2, d3)))
return false;
}
}
}
return true;
}
}

Methods

Pair

Full name: jfreerails.util.Pair

Documentation

/**
* A generic class representing a pair of two elements of types A and B.
* This class provides methods to access the elements, check equality, and generate a string representation.
*
* @see java.util.Objects for equality checks
*/

Source Code

public class Pair<A, B> {
private A e1;
private B e2;
public Pair(A e1, B e2) {
this.e1 = e1;
this.e2 = e2;
}
public boolean equals(Pair<A, B> other) {
if (this == other)
return true;
if (null == other)
return false;
return (e1.equals(other.e1) && e2.equals(other.e2));
}
public String toString() {
return "(" + e1.toString() + ", " + e2.toString() + ")";
}
public A getA() {
return e1;
}
public B getB() {
return e2;
}
}

Immutable

Full name: jfreerails.util.Immutable

Documentation

/**
* @author Luke 04-Jul-2005
*/

Source Code

/**
* @author Luke 04-Jul-2005
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Immutable {
}

Methods

No methods found

GameModel

Full name: jfreerails.util.GameModel

Documentation

/**
* Defines a standard method to update the game world.
*
* @author Luke
*
*/

Source Code

/**
* Defines a standard method to update the game world.
*
* @author Luke
*
*/
public interface GameModel {
void update();
}

Methods

List1DImpl

Full name: jfreerails.util.List1DImpl

Documentation

/**
* A concrete implementation of the List1D interface, providing a one-dimensional list
* with standard operations such as add, remove, get, and set. This implementation uses
* an ArrayList to store elements and provides basic list functionality.
*
* @see List1D
* @see java.util.ArrayList
*/

Source Code

public class List1DImpl<T> implements List1D<T> {
private static final long serialVersionUID = 8285123045287237133L;
private final ArrayList<T> elementData;
public List1DImpl() {
elementData = new ArrayList<T>();
}
public List1DImpl(int initialSize) {
elementData = new ArrayList<T>();
for (int i = 0; i < initialSize; i++) {
elementData.add(null);
}
}
public int size() {
return elementData.size();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof List1D))
return false;
return Lists.equals(this, (List1D) obj);
}
@Override
public int hashCode() {
return size();
}
public T get(int i) {
return elementData.get(i);
}
public T removeLast() {
int last = elementData.size() - 1;
return elementData.remove(last);
}
public int add(T element) {
elementData.add(element);
return elementData.size() - 1;
}
public void set(int i, T element) {
elementData.set(i, element);
}
}

FlowRateOutputStream

Full name: jfreerails.util.FlowRateOutputStream

Documentation

/**
* A FilterOutputStream that measures flow rate.
*
* @author Patrice Espie Licensing: LGPL
*/

Source Code

/**
* A FilterOutputStream that measures flow rate.
*
* @author Patrice Espie Licensing: LGPL
*/
public class FlowRateOutputStream extends FilterOutputStream implements
Runnable {
private static final Logger logger = Logger
.getLogger(FlowRateOutputStream.class.getName());
public FlowRateOutputStream(OutputStream out, String streamName) {
this(out, streamName, 60, 1000);
}
public FlowRateOutputStream(OutputStream out, String streamName,
int measureDuration, int measureInterval) {
super(out);
byteSentCumul = 0L;
totalByteSent = 0L;
previousTotalByteSent = 0L;
openTimeMillis = System.currentTimeMillis();
nextFree = 0;
nbUsed = 0;
running = false;
closeRequested = false;
byteSent = new long[measureDuration];
this.measureInterval = measureInterval;
this.streamName = streamName;
if (this.measureInterval == 0) {
showTrace = false;
this.measureInterval = 1000L;
} else {
showTrace = true;
}
(new Thread(this)).start();
}
public FlowRateOutputStream(OutputStream out) {
this(out, "FlowRateOutputStream", 60, 1000);
}
@Override
public void close() throws IOException {
closeRequested = true;
super.close();
do {
try {
Thread.currentThread();
Thread.sleep(50L);
} catch (InterruptedException interruptedexception) {
}
} while (running);
logger.info(String.valueOf(String.valueOf((new StringBuffer("Stream "))
.append(streamName).append(": Open duration = ").append(
(System.currentTimeMillis() - openTimeMillis) / 1000D)
.append(", Byte sent = ").append(totalByteSent).append(" (")
.append((int) (totalByteSent / 1024D)).append(
" Ko), overall flow rate = ").append(
overallRateString()).append(" Ko/s"))));
}
@Override
public void write(byte[] b) throws IOException {
super.out.write(b, 0, b.length);
totalByteSent += b.length;
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
super.out.write(b, off, len);
totalByteSent += len;
}
@Override
public void write(int b) throws IOException {
super.out.write(b);
totalByteSent++;
}
public int currentRate() throws IOException {
return (int) (byteSentCumul / 1024D / (nbUsed * (measureInterval / 1000D)));
}
public int overallRate() throws IOException {
return (int) (totalByteSent / 1024D / ((System.currentTimeMillis() - openTimeMillis) / 1000D));
}
public String overallRateString() throws IOException {
double d = totalByteSent / 1024D
/ ((System.currentTimeMillis() - openTimeMillis) / 1000D);
return decimalFormat.format(d);
}
public String currentRateString() {
double d = (byteSentCumul / 1024D / (nbUsed * (measureInterval / 1000D)));
return decimalFormat.format(d);
}
public void run() {
if (running) {
throw new Error("Starting thread task on an already-started object");
}
if (measureInterval == 0x7fffffffffffffffL) {
return;
}
running = true;
try {
do {
try {
Thread.currentThread();
Thread.sleep(measureInterval);
} catch (InterruptedException interruptedexception) {
}
if (!closeRequested) {
long totalByteSentCopy = totalByteSent;
long byteSentThisTime = totalByteSentCopy
- previousTotalByteSent;
previousTotalByteSent = totalByteSentCopy;
byteSentCumul -= byteSent[nextFree];
byteSent[nextFree] = byteSentThisTime;
byteSentCumul += byteSentThisTime;
nextFree = (nextFree + 1) % byteSent.length;
nbUsed = Math.min(byteSent.length, nbUsed + 1);
if (showTrace) {
logger
.info(String
.valueOf(String
.valueOf((new StringBuffer(
"Stream "))
.append(streamName)
.append(
": Open duration = ")
.append(
(System
.currentTimeMillis() - openTimeMillis) / 1000D)
.append(
", Byte sent = ")
.append(totalByteSent)
.append(" (")
.append(
(int) (totalByteSent / 1024D))
.append(
" Ko), current flow rate = ")
.append(
currentRateString())
.append(" Ko/s"))));
}
}
} while (!closeRequested);
// } catch (IOException ioexception) {
} finally {
running = false;
}
}
private long[] byteSent;
private long byteSentCumul;
private long totalByteSent;
private long previousTotalByteSent;
private long openTimeMillis;
private long measureInterval;
private int nextFree;
private int nbUsed;
private boolean running;
private boolean closeRequested;
private String streamName;
private boolean showTrace;
private DecimalFormat decimalFormat = new DecimalFormat("0.00");
}

List2D

Full name: jfreerails.util.List2D

Documentation

/**
* A two-dimensional list interface that supports dynamic resizing and element manipulation.
* This interface provides methods to manage elements in a 2D structure, allowing for
* operations such as adding, removing, and retrieving elements along both dimensions.
*
* @author Your Name
* @since 1.0
* @see java.util.List
*/

Source Code

public interface List2D<T> extends Serializable {
int sizeD1();
int sizeD2(int d1);
T get(int d1, int d2);
T removeLastD2(int d1);
int removeLastD1();
int addD1();
int addD2(int d1, T element);
void set(int d1, int d2, T element);
}

CompressedOutputStream

Full name: jfreerails.util.CompressedOutputStream

Documentation

/**
* A FilterOutputStream for sending compressed data over a network connection.
* Note that standard ZipOutputStream and java.util.zip.GZipOutputStream don't
* guarantee that flush sends out all the data written so far, which leads to
* deadlocks in request-response-based protocols.
*
* @author Patrice Espie Licensing: LGPL
*/

Source Code

/**
* A FilterOutputStream for sending compressed data over a network connection.
* Note that standard ZipOutputStream and java.util.zip.GZipOutputStream don't
* guarantee that flush sends out all the data written so far, which leads to
* deadlocks in request-response-based protocols.
*
* @author Patrice Espie Licensing: LGPL
*/
public class CompressedOutputStream extends FilterOutputStream {
public CompressedOutputStream(OutputStream out) {
super(out);
buffer = new byte[0x7d000];
compBuffer = new byte[(int) (buffer.length * 1.2D)];
writeIndex = 0;
deflater = new Deflater(9);
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
int written = 0;
do {
if (written >= len) {
break;
}
int toWrite = Math.min(len - written, buffer.length - writeIndex);
System.arraycopy(b, off + written, buffer, writeIndex, toWrite);
written += toWrite;
writeIndex += toWrite;
if (writeIndex >= buffer.length * 0.80000000000000004D) {
flush();
}
} while (true);
}
@Override
public void write(int b) throws IOException {
if (writeIndex >= buffer.length * 0.80000000000000004D) {
flush();
}
buffer[writeIndex++] = (byte) b;
}
@Override
public void flush() throws IOException {
int compSize = 0;
boolean sendCompressed;
if (writeIndex > 150) {
deflater.reset();
deflater.setInput(buffer, 0, writeIndex);
deflater.finish();
if (compBuffer.length < writeIndex * 2 + 40960) {
compBuffer = new byte[writeIndex * 2 + 40960];
}
compSize = deflater.deflate(compBuffer);
if (compSize <= 0) {
throw new IOException("Compression exception");
}
sendCompressed = compSize < writeIndex;
} else {
sendCompressed = false;
}
if (sendCompressed) {
super.out.write(1);
super.out.write(writeIndex >> 24 & 0xff);
super.out.write(writeIndex >> 16 & 0xff);
super.out.write(writeIndex >> 8 & 0xff);
super.out.write(writeIndex & 0xff);
super.out.write(compSize >> 24 & 0xff);
super.out.write(compSize >> 16 & 0xff);
super.out.write(compSize >> 8 & 0xff);
super.out.write(compSize & 0xff);
super.out.write(compBuffer, 0, compSize);
super.out.flush();
writeIndex = 0;
} else if (writeIndex > 0) {
super.out.write(0);
super.out.write(writeIndex >> 24 & 0xff);
super.out.write(writeIndex >> 16 & 0xff);
super.out.write(writeIndex >> 8 & 0xff);
super.out.write(writeIndex & 0xff);
super.out.write(buffer, 0, writeIndex);
super.out.flush();
writeIndex = 0;
}
}
private byte[] buffer;
private byte[] compBuffer;
private int writeIndex;
private Deflater deflater;
}

InstanceControlled

Full name: jfreerails.util.InstanceControlled

Documentation

/**
* @author Luke 04-Jul-2005
*/

Source Code

/**
* @author Luke 04-Jul-2005
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface InstanceControlled {
}

Methods

No methods found

List2DImpl

Full name: jfreerails.util.List2DImpl

Documentation

/**
* Implementation of the List2D interface providing a two-dimensional list structure.
* This class manages a list of lists, allowing operations on both dimensions (d1 and d2).
* It supports adding, removing, and accessing elements, as well as equality checks and hash code generation.
*
* @author [Author Name]
* @since 1.0
*
* @see List2D
* @see java.util.ArrayList
*/

Source Code

public class List2DImpl<T> implements List2D<T> {
private static final long serialVersionUID = 7614246212629595959L;
private final ArrayList<ArrayList<T>> elementData = new ArrayList<ArrayList<T>>();
public List2DImpl(int d1){
for(int i = 0; i < d1; i++){
elementData.add(new ArrayList<T>());
}
}
public int sizeD1() {
return elementData.size();
}
public int sizeD2(int d1) {
return elementData.get(d1).size();
}
public T get(int d1, int d2) {
return elementData.get(d1).get(d2);
}
public T removeLastD2(int d1) {
int last = elementData.get(d1).size() -1;
T element = elementData.get(d1).get(last);
elementData.get(d1).remove(last);
return element;
}
public int removeLastD1() {
int last = elementData.size() -1;
if(sizeD2(last) != 0)
throw new IllegalStateException(String.valueOf(last));
elementData.remove(last);
return last;
}
public int addD1() {
elementData.add(new ArrayList<T>());
return elementData.size() -1;
}
public int addD2(int d1, T element) {
ArrayList<T> d2 = elementData.get(d1);
int index = d2.size();
d2.add(element);
return index;
}
public void set(int d1, int d2, T element) {
elementData.get(d1).set(d2, element);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof List2D)) {
return false;
}
return Lists.equals(this, (List2D)obj);
}
@Override
public int hashCode() {
return sizeD1();
}
}

ListKey

Full name: jfreerails.util.ListKey

Documentation

/**
* <strong>ListKey</strong> represents a composite key used to uniquely identify and order elements in a list structure.
* It encapsulates a type (Element or EndPoint), a list identifier (Enum), and an array of indices, providing methods for
* equality checks, ordering, and string representation. This class is designed to be used as a key in collections requiring
* precise comparison and serialization capabilities.
*
* @author [Author Name]
* @since 1.0
* @see java.util.Enum
* @see java.lang.Comparable
* @see java.io.Serializable
*/

Source Code

public class ListKey implements Comparable<ListKey>, Serializable{
private static final long serialVersionUID = -4939641035786937927L;
public enum Type {
Element, EndPoint
}
private final Type type;
private final int[] index;
private final Enum listID;
public ListKey(Type t, Enum listID, int... i){
type = t;
index = i.clone();
this.listID = listID;
}
public int[] getIndex() {
return index.clone();
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ListKey))
return false;
final ListKey listKey = (ListKey) o;
if (!Arrays.equals(index, listKey.index))
return false;
if (!listID.equals(listKey.listID))
return false;
if (!type.equals(listKey.type))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = type.hashCode();
result = 29 * result + listID.hashCode();
return result;
}
public Type getType() {
return type;
}
public int compareTo(ListKey o) {
if(o.listID != listID)
return o.listID.ordinal() - listID.ordinal();
if(index.length != o.index.length)
return index.length -o.index.length;
for (int i = 0; i < index.length; i++) {
if(index[i] != o.index[i])
return index[i] -o.index[i];
}
if(o.type != type)
return o.type.ordinal() - type.ordinal();
return 0;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(listID);
sb.append(" ");
sb.append(type);
sb.append(" index ");
for (int i = 0; i < index.length; i++) {
sb.append("[");
sb.append(index[i]);
sb.append("]");
}
return sb.toString();
}
public Enum getListID() {
return listID;
}
}

List1DDiff

Full name: jfreerails.util.List1DDiff

Documentation

/**
* <strong>List1DDiff</strong> provides a 1-dimensional list diff view, allowing modification of an underlying list while tracking changes.
* This class delegates most operations to the superclass {@link ListXDDiffs} but overrides methods to ensure 1D indexing and behavior.
* It wraps an underlying {@link List1D} instance, exposing its elements through diff-aware access.
*
* @author YourName
* @since 1.0
* @see ListXDDiffs
* @see List1D
*/

Source Code

public class List1DDiff<T> extends ListXDDiffs<T> implements List1D<T> {
private static final long serialVersionUID = -6058018396890452219L;
private final List1D<T> underlyingList;
public List1DDiff(SortedMap<ListKey, Object> diffs, List1D<T> list,
Enum listID) {
super(diffs, listID);
underlyingList = list;
}
public T get(int i) {
return get(new int[] { i });
}
@Override
Object getUnderlyingList() {
return underlyingList;
}
public int size() {
return super.size(new int[0]);
}
@Override
T uGet(int... i) {
if (i.length != 1)
throw new IllegalArgumentException();
return underlyingList.get(i[0]);
}
public int add(T element) {
return super.addElement(element);
}
public T removeLast() {
return super.removeLast();
}
public void set(int i, T element) {
super.set(element, i);
}
@Override
int getUnderlyingSize(int... dim) {
if (dim.length != 0)
throw new IllegalArgumentException(String.valueOf(dim.length));
return underlyingList.size();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof List1D))
return false;
return Lists.equals(this, (List1D) obj);
}
@Override
public int hashCode() {
return size();
}
}

IntArray

Full name: jfreerails.util.IntArray

Documentation

/**
* Growable <code>int</code> array with type specific access methods. This
* implementation is unsynchronized in order to provide the best possible
* performance for typical usage scenarios, so explicit synchronization must be
* implemented by a wrapper class or directly by the application in cases where
* instances are modified in a multithreaded environment. See the base classes
* for other details of the implementation.
*
* @author Dennis M. Sosnoski
* @version 1.0
*/

Source Code

/**
* Growable <code>int</code> array with type specific access methods. This
* implementation is unsynchronized in order to provide the best possible
* performance for typical usage scenarios, so explicit synchronization must be
* implemented by a wrapper class or directly by the application in cases where
* instances are modified in a multithreaded environment. See the base classes
* for other details of the implementation.
*
* @author Dennis M. Sosnoski
* @version 1.0
*/
public class IntArray extends ArrayBase implements Serializable {
private static final long serialVersionUID = 3258408426391418681L;
/** The underlying array used for storing the data. */
protected int[] baseArray;
/**
* Constructor with full specification.
*
* @param size
* number of <code>int</code> values initially allowed in array
* @param growth
* maximum size increment for growing array
*/
public IntArray(int size, int growth) {
super(size, growth, int.class);
}
/**
* Constructor with only initial size specified.
*
* @param size
* number of <code>int</code> values initially allowed in array
*/
public IntArray(int size) {
super(size, int.class);
}
/**
* Default constructor.
*/
public IntArray() {
this(DEFAULT_SIZE);
}
/**
* Copy (clone) constructor.
*
* @param base
* instance being copied
*/
public IntArray(IntArray base) {
super(base);
}
/**
* Get the backing array. This method is used by the type-agnostic base
* class code to access the array used for type-specific storage.
*
* @return backing array object
*/
@Override
protected final Object getArray() {
return baseArray;
}
/**
* Set the backing array. This method is used by the type-agnostic base
* class code to set the array used for type-specific storage.
*
*/
@Override
protected final void setArray(Object array) {
baseArray = (int[]) array;
}
/**
* Add a value to the array, appending it after the current values.
*
* @param value
* value to be added
* @return index number of added element
*/
public final int add(int value) {
int index = getAddIndex();
baseArray[index] = value;
return index;
}
/**
* Add a value at a specified index in the array.
*
* @param index
* index position at which to insert element
* @param value
* value to be inserted into array
*/
public void add(int index, int value) {
makeInsertSpace(index);
baseArray[index] = value;
}
/**
* Retrieve the value present at an index position in the array.
*
* @param index
* index position for value to be retrieved
* @return value from position in the array
*/
public final int get(int index) {
if (index < countPresent) {
return baseArray[index];
}
throw new ArrayIndexOutOfBoundsException("Invalid index value");
}
/**
* Set the value at an index position in the array.
*
* @param index
* index position to be set
* @param value
* value to be set
*/
public final void set(int index, int value) {
if (index < countPresent) {
baseArray[index] = value;
} else {
throw new ArrayIndexOutOfBoundsException("Invalid index value");
}
}
/**
* Constructs and returns a simple array containing the same data as held in
* this growable array.
*
* @return array containing a copy of the data
*/
public int[] toArray() {
return (int[]) buildArray(int.class, 0, countPresent);
}
/**
* Constructs and returns a simple array containing the same data as held in
* a portion of this growable array.
*
* @param offset
* start offset in array
* @param length
* number of characters to use
* @return array containing a copy of the data
*/
public int[] toArray(int offset, int length) {
return (int[]) buildArray(int.class, offset, length);
}
/**
* Duplicates the object with the generic call.
*
* @return a copy of the object
*/
@Override
public Object clone() {
return new IntArray(this);
}
}

ArrayBase

Full name: jfreerails.util.ArrayBase

Documentation

/**
* Base class for type-specific growable array classes with any type of values
* (including primitive types). This class builds on the basic structure
* provided by <code>GrowableBase</code>, specializing it for usage as a
* growable array. See the base class description for details of the
* implementation.
* <p>
*
* Growable arrays based on this class are not synchronized in order to provide
* the best possible performance for typical usage scenarios, so explicit
* synchronization must be implemented by the subclass or the application in
* cases where they are to be modified in a multithreaded environment.
* <p>
*
* Subclasses need to implement the abstract methods defined by the base class
* for working with the data array, as well as the actual data access methods
* (at least the basic <code>add()</code>, <code>get()</code>,
* <code>set()</code>, and <code>toArray()</code> methods).
*
* @author Dennis M. Sosnoski
* @version 1.0
*/

Source Code

/**
* Base class for type-specific growable array classes with any type of values
* (including primitive types). This class builds on the basic structure
* provided by <code>GrowableBase</code>, specializing it for usage as a
* growable array. See the base class description for details of the
* implementation.
* <p>
*
* Growable arrays based on this class are not synchronized in order to provide
* the best possible performance for typical usage scenarios, so explicit
* synchronization must be implemented by the subclass or the application in
* cases where they are to be modified in a multithreaded environment.
* <p>
*
* Subclasses need to implement the abstract methods defined by the base class
* for working with the data array, as well as the actual data access methods
* (at least the basic <code>add()</code>, <code>get()</code>,
* <code>set()</code>, and <code>toArray()</code> methods).
*
* @author Dennis M. Sosnoski
* @version 1.0
*/
public abstract class ArrayBase extends GrowableBase implements Serializable {
/** The number of values currently present in the array. */
protected int countPresent;
/**
* Constructor with full specification.
*
* @param size
* number of elements initially allowed in array
* @param growth
* maximum size increment for growing array
* @param type
* array element type
*/
public ArrayBase(int size, int growth, Class type) {
super(size, growth, type);
}
/**
* Constructor with partial specification.
*
* @param size
* number of elements initially allowed in array
* @param type
* array element type
*/
public ArrayBase(int size, Class type) {
this(size, Integer.MAX_VALUE, type);
}
/**
* Copy (clone) constructor.
*
* @param base
* instance being copied
*/
public ArrayBase(ArrayBase base) {
super(base);
System.arraycopy(base.getArray(), 0, getArray(), 0, base.countPresent);
countPresent = base.countPresent;
}
/**
* Get the array for another instance of this class. This is a convenience
* method to allow subclasses access to the backing array of other
* subclasses.
*
* @param other
* subclass instance to get array from
* @return backing array object
*/
protected static Object getArray(ArrayBase other) {
return other.getArray();
}
/**
* Gets the array offset for appending a value to those in the array. If the
* underlying array is full, it is grown by the appropriate size increment
* so that the index value returned is always valid for the array in use by
* the time of the return.
*
* @return index position for added element
*/
protected final int getAddIndex() {
int index = countPresent++;
if (countPresent > countLimit) {
growArray(countPresent);
}
return index;
}
/**
* Makes room to insert a value at a specified index in the array.
*
* @param index
* index position at which to insert element
*/
protected void makeInsertSpace(int index) {
if (index >= 0 && index <= countPresent) {
if (++countPresent > countLimit) {
growArray(countPresent);
}
if (index < countPresent - 1) {
Object array = getArray();
System.arraycopy(array, index, array, index + 1, countPresent
- index - 1);
}
} else {
throw new ArrayIndexOutOfBoundsException("Invalid index value");
}
}
/**
* Remove a range of value from the array. The index positions for values
* above the range removed are decreased by the number of values removed.
*
* @param from
* index number of first value to be removed
* @param to
* index number past last value to be removed
*/
public void remove(int from, int to) {
if (from >= 0 && to <= countPresent && from <= to) {
if (to < countPresent) {
int change = from - to;
Object base = getArray();
System.arraycopy(base, to, base, from, countPresent - to);
discardValues(countPresent + change, countPresent);
countPresent += change;
}
} else {
throw new ArrayIndexOutOfBoundsException("Invalid remove range");
}
}
/**
* Remove a value from the array. All values above the index removed are
* moved down one index position.
*
* @param index
* index number of value to be removed
*/
public void remove(int index) {
remove(index, index + 1);
}
/**
* Get the number of values currently present in the array.
*
* @return count of values present
*/
public final int size() {
return countPresent;
}
/**
* Sets the number of values currently present in the array. If the new size
* is greater than the current size, the added values are initialized to the
* default values. If the new size is less than the current size, all values
* dropped from the array are discarded.
*
* @param count
* number of values to be set
*/
public void setSize(int count) {
if (count > countLimit) {
growArray(count);
} else if (count < countPresent) {
discardValues(count, countPresent);
}
countPresent = count;
}
/**
* Set the array to the empty state.
*/
public final void clear() {
setSize(0);
}
/**
* Constructs and returns a simple array containing the same data as held in
* a portion of this growable array. This override of the base class method
* checks that the portion specified actually has data present before
* constructing the returned array.
*
* @param type
* element type for constructed array
* @param offset
* start offset in array
* @param length
* number of characters to use
* @return array containing a copy of the data
*/
@Override
protected Object buildArray(Class type, int offset, int length) {
if (offset + length <= countPresent) {
return super.buildArray(type, offset, length);
}
throw new ArrayIndexOutOfBoundsException();
}
}

List3D

Full name: jfreerails.util.List3D

Documentation

/**
* A 3D list interface that provides methods for managing and accessing elements in three dimensions.
* This interface extends {@link java.io.Serializable} to support serialization of 3D list instances.
* It includes operations for retrieving sizes, accessing elements, and modifying the structure along each dimension.
*
* @see java.io.Serializable
*/

Source Code

public interface List3D<T> extends Serializable {
int sizeD1();
int sizeD2(int d1);
int sizeD3(int d1, int d2);
T get(int d1, int d2, int d3);
List<T> get(int d1, int d2);
T removeLastD3(int d1, int d2);
void removeLastD1();
void removeLastD2(int d1);
int addD1();
int addD2(int d1);
int addD3(int d1, int d2, T element);
void set(int d1, int d2, int d3, T element);
}

List3DDiff

Full name: jfreerails.util.List3DDiff

Documentation

/**
* Represents a 3-dimensional list diff, providing a delta view of changes to a 3D list structure.
* This class delegates operations to its superclass {@link ListXDDiffs} while exposing the underlying
* 3D list via {@link #getUnderlyingList()}. It supports dimension manipulation, element access,
* and size queries for multi-dimensional indexing.
*
* @author [Author Name]
* @see ListXDDiffs
* @see List3D
* @see Lists
*/

Source Code

public class List3DDiff<T> extends ListXDDiffs<T> implements List3D<T> {
private static final long serialVersionUID = 14976913635251766L;
private final List3D<T> underlyingList;
public List3DDiff(SortedMap<ListKey, Object> diffs, List3D<T> list,
Enum listID) {
super(diffs, listID);
this.underlyingList = list;
}
public int addD1() {
return super.addDimension();
}
public int addD2(int d1) {
return super.addDimension(d1);
}
public int addD3(int d1, int d2, T element) {
return super.addElement(element, d1, d2);
}
public T get(int d1, int d2, int d3) {
return super.get(d1, d2, d3);
}
@Override
Object getUnderlyingList() {
return underlyingList;
}
@Override
int getUnderlyingSize(int... dim) {
if(dim.length == 0)
return underlyingList.sizeD1();
if(dim.length == 1){
if (underlyingList.sizeD1() <= dim[0])
return -1;
return underlyingList.sizeD2(dim[0]);
}
if(dim.length == 2){
if (underlyingList.sizeD1() <= dim[0])
return -1;
if (underlyingList.sizeD2(dim[0]) <= dim[1])
return -1;
return underlyingList.sizeD3(dim[0], dim[1]);
}
throw new IllegalArgumentException(String.valueOf(dim.length));
}
public void removeLastD1() {
super.removeLastList();
}
public void removeLastD2(int d1) {
super.removeLastList(d1);
}
public T removeLastD3(int d1, int d2) {
return super.removeLast(d1, d2);
}
public void set(int d1, int d2, int d3, T element) {
super.set(element, d1, d2, d3);
}
public int sizeD1() {
return super.size();
}
public int sizeD2(int d1) {
return super.size(d1);
}
public int sizeD3(int d1, int d2) {
return super.size(d1, d2);
}
@Override
T uGet(int... i) {
if (i.length != 3)
throw new IllegalArgumentException();
return underlyingList.get(i[0], i[1], i[2]);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof List3D))
return false;
return Lists.equals(this, (List3D)obj);
}
@Override
public int hashCode() {
return sizeD1();
}
public List<T> get(int d1, int d2) {
List<T> list = new ArrayList<T>();
for(int d3 = 0; d3 < sizeD3(d1, d2); d3++) {
list.add(get(d1, d2, d3));
}
return list;
}
}

ClassLocater

Full name: jfreerails.util.ClassLocater

Documentation

/**
* An essential part of Java - locates any Class, anywhere.
* <P> * This class should have been part of the JDK for the last 7 years, but Sun
* hasn't added it, so we did it instead :).
* <P>
* No static methods since people are already using this in environments where
* they need multiple separately configured copies running in parallel. Sun's
* JVM design (caching classloaders) ensure that cached class data is
* automatically shared between instances; it could be made faster by storing an
* internal DB rather than re-instantiating, but the time-savings are minuscule
* (might save some milliseconds if you have 1000 classes).
* <p>Usage Tips</p>
* If you are using this to automatically find all plugins that your users have
* for your API then the easiest thing to do is declare a package that plugins
* are in. Note: you could also declare a naming convention, as many open-source
* projects have done when writing poor alternatives to this method. This is bad
* practice, since java already has a naming-convention system - packages - and
* we can easily use that - but it required more coding to make it work. There
* are cases where you cannot use the packages this way (though personally I'd
* recommend you re-think your design in that case), and in those cases you can
* easily use a class-naming convention instead. So, everyone should be happy.
* <P>
* If you reserve a package for plugins, e.g. declare that all plugins must be
* in package "org.javagamesfactory.plugins", then you simply pass something
* like "org\.javagamesfactory\.plugins\..*" in (regex meaning "all things in
* that package). This class will actually find all things in that package
* <i>even if they are in different copies of that package, in different JAR
* files, or different directories</i>.
* <P>
* To use a naming convention, e.g. all plugin class names start with the text
* "PLUGIN" you would do something like: ".*\.PLUGIN.*".
* <p>
* In all cases, note the fact that regex's have special meaning for dot, so you
* have to escape it when you just mean a full-stop. Read the java API docs for
* java.util.regex for more information
*
* @see java.util.regex.Pattern
*/

Source Code

/**
* An essential part of Java - locates any Class, anywhere.
* <P> * This class should have been part of the JDK for the last 7 years, but Sun
* hasn't added it, so we did it instead :).
* <P>
* No static methods since people are already using this in environments where
* they need multiple separately configured copies running in parallel. Sun's
* JVM design (caching classloaders) ensure that cached class data is
* automatically shared between instances; it could be made faster by storing an
* internal DB rather than re-instantiating, but the time-savings are minuscule
* (might save some milliseconds if you have 1000 classes).
* <p>Usage Tips</p>
* If you are using this to automatically find all plugins that your users have
* for your API then the easiest thing to do is declare a package that plugins
* are in. Note: you could also declare a naming convention, as many open-source
* projects have done when writing poor alternatives to this method. This is bad
* practice, since java already has a naming-convention system - packages - and
* we can easily use that - but it required more coding to make it work. There
* are cases where you cannot use the packages this way (though personally I'd
* recommend you re-think your design in that case), and in those cases you can
* easily use a class-naming convention instead. So, everyone should be happy.
* <P>
* If you reserve a package for plugins, e.g. declare that all plugins must be
* in package "org.javagamesfactory.plugins", then you simply pass something
* like "org\.javagamesfactory\.plugins\..*" in (regex meaning "all things in
* that package). This class will actually find all things in that package
* <i>even if they are in different copies of that package, in different JAR
* files, or different directories</i>.
* <P>
* To use a naming convention, e.g. all plugin class names start with the text
* "PLUGIN" you would do something like: ".*\.PLUGIN.*".
* <p>
* In all cases, note the fact that regex's have special meaning for dot, so you
* have to escape it when you just mean a full-stop. Read the java API docs for
* java.util.regex for more information
*
* @see java.util.regex.Pattern
*/
public class ClassLocater {
protected static Logger logger = Logger.getLogger("jgf.classlocater");
protected LinkedList<String> skipPrefixes = new LinkedList<String>();
/**
* Finds all classes that implement or extend a given class name, and
* instantiates precisely one copy of each
*
* @param className
* fully qualified class or interface to find subclasses of, e.g.
* "java.lang.String"
* @param skipPrefixes
* prefixes of fully qualified packages or class names to
* completely ignore (i.e. not bother to check), making it
* faster, e.g. "java.", "com.sun"
* @return instantiated objects
*/
public static List instantiateOneOfEach(String className,
String[] skipPrefixes) {
Class[] classes = null;
LinkedList<Object> instances = new LinkedList<Object>();
try {
ClassLocater locater = new ClassLocater();
for (int i = 0; i < skipPrefixes.length; i++) {
locater.addSkipPrefix(skipPrefixes[i]);
}
classes = locater.getSubclassesOf(Class.forName(className));
logger.info("Found " + classes.length + " classes that implement "
+ className + "...");
if (logger.getLevel().equals(Level.FINE))
for (int i = 0; i < classes.length; i++) {
logger.fine("Found " + classes[i].getName()
+ " that implements " + className + "...");
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Attempting to find " + className
+ " implementers", e);
}
// Iterate through all, instantiating them
logger.fine("Instantiating each class");
for (int i = 0; i < classes.length; i++) {
try {
Object o = classes[i].newInstance();
instances.add(o);
} catch (Throwable e) {
logger.log(Level.SEVERE, "Failed to process: "
+ classes[i].getName(), e);
}
}
return instances;
}
/**
* Automatically adds sun's classes, the java library classes, and the
* Apache log4j classes (a lib used by ClassLocater!) to the skip list; it's
* very unlikely that you're trying to locate any of these!
*/
public ClassLocater() {
addSkipPrefix("org.apache.log4j.");
addSkipPrefix("com.sun.");
addSkipPrefix("java");
addSkipPrefix("junit");
}
/**
* Adds a prefix for classes (and packages) to completely ignore, based on
* their package + class name.
* <p>
* For example, "org.apache.log4j".
* <P>
* The advantage of this method is that you don't have to bother with regex
* syntax. Also, it is remembered between calls to getSubclassesOf - so it's
* useful if you know you never care about certain packages.
*
* @param s
* prefix of fully qualified class names to ignore
*/
public void addSkipPrefix(String s) {
skipPrefixes.add(s);
}
/**
* Find all instances of the given <code>Class</code> or interface by
* loading all classes on the class path.
* <P>
* Delegates to the other version, but passing in ".*" as the regex, i.e.
* "anything at all"
*
* @param targetType
* the superclass of all returned classes.
* @return an array of all subclasses of <code>targetType</code>
*/
public Class[] getSubclassesOf(Class targetType) {
return getSubclassesOf(targetType, ".*");
}
/**
* Find all subclasses of the given <code>Class</code> or interface by
* loading only those classes with names that match the given regular
* expression.
* <P>
* Once all classes have been checked, it will output at WARN a list of all
* the classes that were referenced by other classes but are not installed
* in the classpath. This can be incredibly useful - it catches situations
* where e.g. you thought a class was on the classpath but you put it in the
* wrong directory etc.
* <P>
* It can also be very annoying because java uses dynamic linking so it is
* LEGAL for many classes to be missing, just so long as you never use them
* at runtime. Because this class tries to use *every* class, it triggers
* errors on lots that you don't care about - use addSkipPrefix( class or
* package you dont use even though its on the classpath ) and they will be
* skipped (i.e. not even examined by this method).
* <P>
* OR improve your regex so that it is more selective about the packages
* where your classes could conceivable be located!
*
* @param targetType
* the superclass of all returned classes.
* @param regex
* a regular expression that will match with every subclass
* @return an array of all subclasses of <code>targetType</code>
*/
@SuppressWarnings("unchecked")
public Class[] getSubclassesOf(Class targetType, String regex) {
logger.info("Looking for all classes with names matching regex = "
+ regex + " and which are subtypes of " + targetType.getName());
StringBuffer sbSkips = new StringBuffer();
for (Iterator i2 = skipPrefixes.iterator(); i2.hasNext();) {
sbSkips.append(i2.next().toString() + "*");
if (i2.hasNext())
sbSkips.append(", ");
}
logger.info("...unless they match: " + sbSkips.toString());
LinkedList<Class> matches = new LinkedList<Class>();
HashMap<String, LinkedList<String>> missingRequiredClasses = new HashMap<String, LinkedList<String>>();
// maps class name to list of classes that needed it
logger.fine("Creating ClassPath object to do class search...");
ClassPath cp = new ClassPath();
logger.fine("Iterating through all classes in ClassPath...");
for (Iterator iter = cp.getAllClassNames().iterator(); iter.hasNext();) {
String className = (String) iter.next();
boolean skip = false;
for (Iterator i2 = skipPrefixes.iterator(); i2.hasNext();) {
String prefix = (String) i2.next();
if (className.startsWith(prefix)) {
logger.fine("Skipping class = " + className
+ " because it has a prefix of " + prefix);
skip = true;
break;
}
}
if (skip)
continue;
logger.fine("Processing class: " + className);
if (className.matches(regex)
&& !className.equals(targetType.getName())) {
logger
.fine("...matches regex; instantiating and checking type");
Class clazz = null;
try {
clazz = Class.forName(className);
}
/*
* catch (ClassNotFoundException cnfx ) { continue; }
*/
catch (NoClassDefFoundError cnfx) {
/*
* This is ridiculous. Please, everyone, ask sun to add a
* "getMissingClass()" method to NoClassDefFoundError: Sun,
* you have had TEN YEARS to fix this!
*/
if (cnfx.getMessage() == null) {
logger
.log(
Level.WARNING,
"NoClassDefFoundError but Sun didn't fill-in the message; no idea which class it was; ignoring it and moving on",
cnfx);
continue;
}
String missingClassName = cnfx.getMessage().replace('/',
'.');
LinkedList<String> misses = missingRequiredClasses
.get(missingClassName);
if (misses == null) {
misses = new LinkedList<String>();
missingRequiredClasses.put(missingClassName, misses);
}
misses.add(className);
continue;
} catch (UnsatisfiedLinkError cnfx) {
continue;
} catch (Throwable t) {
logger.log(Level.WARNING,
"Unexpected error - REMOVING this class ("
+ className + ") without checking it", t);
continue;
} finally {
if (clazz != null && targetType.isAssignableFrom(clazz)) {
logger
.fine(className
+ " matches and is correct type; adding to results");
matches.add(clazz);
}
}
}
}
if (missingRequiredClasses.size() > 0) {
logger
.warning("The following classes were needed by some of the classes I found, but could not themselves be found."
+ "Check you have the required libraries, that they are on the classpath, and that all JAR's are in your manifest as needed");
logger
.warning("If you don't care about some of the classes that used these missing classes, add the users to the skip list and you will get no errors from them");
for (Iterator<String> iter = missingRequiredClasses.keySet()
.iterator(); iter.hasNext();) {
String className = iter.next();
LinkedList<String> neededBy = missingRequiredClasses
.get(className);
StringBuffer sb = new StringBuffer();
for (Iterator<String> iterator = neededBy.iterator(); iterator
.hasNext();) {
String referencingClass = iterator.next();
sb.append(referencingClass);
if (iterator.hasNext())
sb.append(", ");
}
logger.warning("class: " + className + " was needed by class"
+ (neededBy.size() == 1 ? "" : "es") + ": " + sb);
}
}
logger.info("found " + matches.size() + " classes.");
return matches.toArray(new Class[matches.size()]);
}
}

ClassPath

Full name: jfreerails.util.ClassPath

Documentation

/**
* ClassPath finds and records the fully qualified name of every Class on the
* classpath via the system property "java.class.path".
* <p>
* Based on original prototype by duncanIdaho for javagaming.org.
*
* @author adam@jgf
*/

Source Code

/**
* ClassPath finds and records the fully qualified name of every Class on the
* classpath via the system property "java.class.path".
* <p>
* Based on original prototype by duncanIdaho for javagaming.org.
*
* @author adam@jgf
*/
public class ClassPath {
protected Logger logger = Logger.getLogger("jgf.classlocater.classpath");
protected LinkedList<String> pathElementsThatHaveAlreadyBeenProcessed;
protected LinkedList<File> jarsThatHAveAlreadyBeenProcessed;
/**
* create a new ClassPath instance and find all classes on the classpath
*/
public ClassPath() {
}
public List getAllClassNames() {
String path = null;
pathElementsThatHaveAlreadyBeenProcessed = new LinkedList<String>();
jarsThatHAveAlreadyBeenProcessed = new LinkedList<File>();
LinkedList<String> pendingClassPathElements = new LinkedList<String>();
LinkedList<String> processedClassPathElements = new LinkedList<String>();
try {
path = System.getProperty("java.class.path");
} catch (Exception x) {
x.printStackTrace();
}
logger.info("scanning classpath: " + path);
StringTokenizer toke = new StringTokenizer(path, File.pathSeparator);
while (toke.hasMoreTokens()) {
String pathElement = toke.nextToken();
pendingClassPathElements.add(pathElement);
}
for (Iterator<String> iter = pendingClassPathElements.iterator(); iter
.hasNext();) {
String pathElement = iter.next();
LinkedList<String> processPendingElement = processPendingElement(pathElement);
processedClassPathElements.addAll(processPendingElement);
}
return processedClassPathElements;
}
/**
* Clones the supplied list, then goes through it processing every element.
*
*/
protected LinkedList<String> processPendingElement(String pathElement) {
LinkedList<String> discoveredClasses = new LinkedList<String>();
File elementFile = new File(pathElement);
String elementName = elementFile.getAbsolutePath();
// do NOT process dupes
if (pathElementsThatHaveAlreadyBeenProcessed.contains(elementName))
return discoveredClasses;
try {
if (elementName.endsWith(".jar")) {
JarFile jar = null;
Manifest man = null;
jar = new JarFile(elementFile);
man = jar.getManifest();
// Find any nested path elements inside the JAR's own private
// class-path...
if (!(jarsThatHAveAlreadyBeenProcessed.contains(elementFile))) {
if (man != null) {
logger.fine("Jarfile = " + elementFile
+ " was not in jarsalreadydone (size = "
+ jarsThatHAveAlreadyBeenProcessed.size());
jarsThatHAveAlreadyBeenProcessed.add(elementFile);
List extraPathElements = findPathElementsInJar(man,
jar, elementFile);
logger.info("...[" + elementFile + "] contained "
+ extraPathElements.size()
+ " additional path elements");
for (Iterator iter = extraPathElements.iterator(); iter
.hasNext();) {
String element = (String) iter.next();
discoveredClasses
.addAll(processPendingElement(element));
}
}
// ...and add all the direct-listed classes that were in the
// JAR
Enumeration e = jar.entries();
while (e.hasMoreElements()) {
JarEntry entry = (JarEntry) e.nextElement();
if (!entry.isDirectory()
&& entry.getName().endsWith(".class")) {
String className = getClassNameFrom(entry.getName());
discoveredClasses.add(className);
}
}
}
} else if (elementName.endsWith(".zip")) {
discoveredClasses.addAll(getZipContents(elementFile));
} else if (elementName.endsWith(".class")) {
String className = convertToClass(elementFile);
discoveredClasses.add(className);
} else {
discoveredClasses.addAll(getDirectoryContents(elementFile));
}
// Mark this element as having been processed, and do NOT process
// dupes
pathElementsThatHaveAlreadyBeenProcessed.add(elementName);
} catch (Exception e) {
e.printStackTrace();
}
return discoveredClasses;
}
/**
* @param classFile
* a class file listed on the classpath itself.
*/
protected String convertToClass(File classFile) {
return getClassNameFrom(classFile.getName());
}
/**
* replace ANY slashes with dots and remove the .class at the end of the
* file name.
*
* @param entryName
* a file name relative to the classpath. A class of package org
* found in directory bin would be passed into this method as
* "org/MyClass.class"
* @return a fully qualified Class name.
*/
private String getClassNameFrom(String entryName) {
String foo = entryName.replace('/', '.');
foo = foo.replace('\\', '.');
return foo.substring(0, foo.lastIndexOf('.'));
}
/**
* Finds all path elements in the supplied JAR and returns them as a list
*
* @param man
* the manifest of the given jar
* @param jar
* the jar associated with the given manifest.
*/
protected LinkedList<String> findPathElementsInJar(Manifest man,
JarFile jar, File jarFile) {
LinkedList<String> result = new LinkedList<String>();
Attributes atts = man.getMainAttributes();
Set keys = atts.keySet();
Iterator i = keys.iterator();
while (i.hasNext()) {
Object key = i.next();
String value = (String) atts.get(key);
logger.fine(jar.getName() + " " + key + ": " + value);
if (key.toString().equals("Class-Path")) {
logger.info("scanning " + jar.getName()
+ "'s manifest classpath: " + value);
StringTokenizer toke = new StringTokenizer(value);
while (toke.hasMoreTokens()) {
String element = toke.nextToken();
if (jarFile.getParent() == null)
result.add(element);
else {
result.add(jarFile.getParent() + File.separator
+ element);
}
}
}
}
return result;
}
/**
* Adds all class names found in the zip mentioned
*
* @param zipFile
*/
protected LinkedList<String> getZipContents(File zipFile) {
LinkedList<String> result = new LinkedList<String>();
ZipFile zip = null;
try {
zip = new JarFile(zipFile);
} catch (IOException iox) {
}
if (zip != null) {
Enumeration e = zip.entries();
while (e.hasMoreElements()) {
ZipEntry entry = (ZipEntry) e.nextElement();
if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
String className = getClassNameFrom(entry.getName());
result.add(className);
}
}
}
return result;
}
/**
* This method takes a top level classpath dir i.e. 'classes' or bin
*
* @param dir
*/
protected LinkedList<String> getDirectoryContents(File dir) {
LinkedList<String> result = new LinkedList<String>();
// drill through contained dirs ... this is expected to be the
// 'classes' or 'bin' dir
File files[] = dir.listFiles();
if (null == files) {
logger.info("dir.listFiles() returned null for " + dir);
return result;
}
for (int i = 0; i < files.length; ++i) {
File f = files[i];
if (f.isDirectory()) {
result.addAll(getDirectoryContents("", f));
} else {
if (f.getName().endsWith(".class"))
result.add(convertToClass(f));
}
}
return result;
}
/**
* This method does the real directory recursion, passing along the the
* corresponding package-path to this directory.
*
* @param pathTo
* the preceding path to this directory
* @param dir
* a directory to search for class files
*/
protected LinkedList<String> getDirectoryContents(String pathTo, File dir) {
LinkedList<String> result = new LinkedList<String>();
String pathToHere = pathTo + dir.getName() + File.separator;
File files[] = dir.listFiles();
for (int i = 0; i < files.length; ++i) {
File f = files[i];
if (f.isDirectory()) {
result.addAll(getDirectoryContents(pathToHere, f));
} else {
if (f.getName().endsWith(".class")) {
String absFilePath = pathToHere + f.getName();
result.add(getClassNameFrom(absFilePath));
}
}
}
return result;
}
}

FreerailsIntIterator

Full name: jfreerails.util.FreerailsIntIterator

Documentation

/**
* Returns a series of ints.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* Returns a series of ints.
*
* @author Luke Lindsay
*
*/
public interface FreerailsIntIterator {
boolean hasNextInt();
int nextInt();
}

SKEYTest

Full name: jfreerails.world.top.SKEYTest

Documentation

/**
* JUnit test.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test.
*
* @author Luke
*
*/
public class SKEYTest extends TestCase {
public void testGetNumberOfKeys() {
assertTrue(SKEY.getNumberOfKeys() > 5);
}
public void testThatAllTheFieldsDefinedInSKEYAreInstancesOFSKEY() {
Field[] fields = SKEY.class.getFields();
for (int i = 0; i < fields.length; i++) {
String name = fields[i].getName();
int modifiers = fields[i].getModifiers();
if (!name.equals("shared")) {
assertTrue("All the fields of SKEY should be static", Modifier
.isStatic(modifiers));
}
assertTrue("All the fields of SKEY should be public", Modifier
.isPublic(modifiers));
assertTrue("All the fields of SKEY should be final", Modifier
.isFinal(modifiers));
try {
if (Modifier.isStatic(modifiers)) {
Object o = fields[i].get(null);
assertTrue("All the fields of SKEY should be instances of"
+ " SKEY", o instanceof SKEY);
}
} catch (IllegalAccessException e) {
assertTrue(false);
}
}
}
}

WorldDiffsTest

Full name: jfreerails.world.top.WorldDiffsTest

Documentation

/**
* JUnit test for WorldDifferences.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test for WorldDifferences.
*
* @author Luke
*
*/
public class WorldDiffsTest extends TestCase {
Player player0 = new Player("player0", 0);
Player player1 = new Player("player1", 1);
public void testSharedLists() {
WorldImpl underlyingWorld = new WorldImpl(10, 10);
CargoType mailCT = new CargoType(10, "Mail", Categories.Mail);
CargoType passengersCT = new CargoType(10, "Passengers",
Categories.Passengers);
underlyingWorld.add(SKEY.CARGO_TYPES, mailCT);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(0, worldDiff.listDiffs());
assertEquals(1, worldDiff.size(SKEY.CARGO_TYPES));
FreerailsSerializable f = worldDiff.get(SKEY.CARGO_TYPES, 0);
assertEquals("The mail cargotype should be accessible.", mailCT, f);
worldDiff.add(SKEY.CARGO_TYPES, passengersCT);
assertEquals(2, worldDiff.size(SKEY.CARGO_TYPES));
assertEquals("2 Diffs: the length of the list + the actual element", 2,
worldDiff.listDiffs());
f = worldDiff.removeLast(SKEY.CARGO_TYPES);
assertEquals(passengersCT, f);
assertEquals(0, worldDiff.listDiffs());
f = worldDiff.removeLast(SKEY.CARGO_TYPES);
assertEquals(mailCT, f);
assertEquals("1 Diff: the list length.", 1, worldDiff.listDiffs());
assertEquals(0 , worldDiff.size(SKEY.CARGO_TYPES));
worldDiff.add(SKEY.CARGO_TYPES, mailCT);
assertEquals(0, worldDiff.listDiffs());
worldDiff.set(SKEY.CARGO_TYPES, 0, passengersCT);
assertEquals("1 Diff: element 0", 1, worldDiff.listDiffs());
}
public void testPlayers() {
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(0, worldDiff.listDiffs());
assertEquals(1, worldDiff.getNumberOfPlayers());
Player p = worldDiff.getPlayer(0);
assertEquals(player0, p);
assertTrue(worldDiff.isPlayer(player0.getPrincipal()));
// Test adding a player.
int n = worldDiff.addPlayer(player1);
assertEquals(1, n);
assertEquals(2, worldDiff.getNumberOfPlayers());
p = worldDiff.getPlayer(1);
assertEquals(player1, p);
assertTrue(worldDiff.isPlayer(player1.getPrincipal()));
}
public void testNonSharedLists() {
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
StationModel station0 = new StationModel();
underlyingWorld.add(player0.getPrincipal(), KEY.STATIONS, station0);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(0, worldDiff.listDiffs());
// First, for an existing player
assertEquals(1, worldDiff.size(player0.getPrincipal(), KEY.STATIONS));
FreerailsSerializable fs = worldDiff.get(player0.getPrincipal(),
KEY.STATIONS, 0);
assertEquals(station0, fs);
// Add a station.
StationModel station1 = new StationModel();
worldDiff.add(player0.getPrincipal(), KEY.STATIONS, station1);
assertEquals(2, worldDiff.size(player0.getPrincipal(), KEY.STATIONS));
fs = worldDiff.get(player0.getPrincipal(), KEY.STATIONS, 1);
assertEquals(station1, fs);
// Change a station.
StationModel station2 = new StationModel();
worldDiff.set(player0.getPrincipal(), KEY.STATIONS, 0, station2);
fs = worldDiff.get(player0.getPrincipal(), KEY.STATIONS, 0);
assertEquals(station2, fs);
// Remove both stations.
fs = worldDiff.removeLast(player0.getPrincipal(), KEY.STATIONS);
assertEquals(station1, fs);
fs = worldDiff.removeLast(player0.getPrincipal(), KEY.STATIONS);
assertEquals(station2, fs);
assertEquals(0, worldDiff.size(player0.getPrincipal(), KEY.STATIONS));
// Add a station again.
int i = worldDiff.add(player0.getPrincipal(), KEY.STATIONS, station1);
assertEquals(0, i);
assertEquals(1, worldDiff.size(player0.getPrincipal(), KEY.STATIONS));
// Second, for a new player
worldDiff.addPlayer(player1);
assertEquals(2, worldDiff.getNumberOfPlayers());
assertEquals(player1, worldDiff.getPlayer(1));
assertEquals(0, worldDiff.size(player1.getPrincipal(), KEY.STATIONS));
worldDiff.add(player1.getPrincipal(), KEY.STATIONS, station1);
assertEquals(1, worldDiff.size(player1.getPrincipal(), KEY.STATIONS));
worldDiff.set(player1.getPrincipal(), KEY.STATIONS, 0, station2);
worldDiff.add(player1.getPrincipal(), KEY.STATIONS, station1);
}
public void testUsingNullElements() {
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
StationModel station0 = new StationModel();
StationModel station1 = null;
underlyingWorld.add(player0.getPrincipal(), KEY.STATIONS, station0);
underlyingWorld.add(player0.getPrincipal(), KEY.STATIONS, station1);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(station0, worldDiff.get(player0
.getPrincipal(), KEY.STATIONS, 0));
assertEquals(station1, worldDiff.get(player0
.getPrincipal(), KEY.STATIONS, 1));
worldDiff.set(player0.getPrincipal(), KEY.STATIONS, 0, station1);
worldDiff.set(player0.getPrincipal(), KEY.STATIONS, 1, station0);
}
public void testItem() {
WorldImpl underlyingWorld = new WorldImpl(10, 10);
StationModel station0 = new StationModel();
StationModel station1 = new StationModel();
underlyingWorld.set(ITEM.GAME_RULES, station0); // why not!
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(station0, worldDiff.get(ITEM.GAME_RULES));
worldDiff.set(ITEM.GAME_RULES, station1);
assertEquals(station1, worldDiff.get(ITEM.GAME_RULES));
}
public void testMap() {
WorldImpl underlyingWorld = new WorldImpl(21, 8);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(21, worldDiff.getMapWidth());
assertEquals(8, worldDiff.getMapHeight());
FreerailsTile tile = (FreerailsTile) underlyingWorld.getTile(2, 2);
assertNotNull(tile);
assertEquals(tile, worldDiff.getTile(2, 2));
FreerailsTile newTile = FreerailsTile.getInstance(999);
worldDiff.setTile(3, 5, newTile);
assertEquals(newTile, worldDiff.getTile(3, 5));
Iterator<ImPoint> it = worldDiff.getMapDiffs();
assertEquals(new ImPoint(3, 5), it.next());
}
public void testAccount(){
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(0, worldDiff.numberOfMapDifferences());
assertEquals(0, worldDiff.listDiffs());
}
public void testEquals(){
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
WorldDiffs a = new WorldDiffs(underlyingWorld);
WorldDiffs b = new WorldDiffs(underlyingWorld);
assertEquals(a, a);
assertEquals(a, b);
assertEquals(a, underlyingWorld);
assertEquals(underlyingWorld, a);
}
public void testGetListDiffs(){
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
WorldDiffs diffs = new WorldDiffs(underlyingWorld);
CityModel city = new CityModel("Bristol", 10, 4);
diffs.add(SKEY.CITIES, city);
Iterator<ListKey> it = diffs.getListDiffs();
@SuppressWarnings("unused")
ListKey lk1 = it.next();
ListKey lk2 = it.next();
assertFalse(it.hasNext());
ListKey expected = new ListKey(Element, SHARED_LISTS, SKEY.CITIES.getKeyID(), 0);
assertEquals(expected, lk2);
}
}

KEYTest

Full name: jfreerails.world.top.KEYTest

Documentation

/**
* JUnit test.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test.
*
* @author Luke
*
*/
public class KEYTest extends TestCase {
public void testGetNumberOfKeys() {
// There were 4 keys when a wrote this test,
// but I expect the number to increase.
assertTrue(KEY.getNumberOfKeys() >= 4);
}
public void testThatAllTheFieldsDefinedInKEYAreInstancesOFKEY() {
Field[] fields = KEY.class.getFields();
for (int i = 0; i < fields.length; i++) {
String name = fields[i].getName();
int modifiers = fields[i].getModifiers();
if (!name.equals("shared")) {
assertTrue("All the fields of KEY should be static", Modifier
.isStatic(modifiers));
}
assertTrue("All the fields of KEY should be public", Modifier
.isPublic(modifiers));
assertTrue("All the fields of KEY should be final", Modifier
.isFinal(modifiers));
try {
if (Modifier.isStatic(modifiers)) {
Object o = fields[i].get(null);
assertTrue("All the fields of KEY should be instances of"
+ " KEY", o instanceof KEY);
}
} catch (IllegalAccessException e) {
assertTrue(false);
}
}
}
public void testToString() {
assertEquals("Key.toString() should return the field name", "TRAINS",
KEY.TRAINS.toString());
}
}

NonNullElementsTest

Full name: jfreerails.world.top.NonNullElementsTest

Documentation

/**
* This junit TestCase tests NonNullElements.
*
* @author Luke
*
*/

Source Code

/**
* This junit TestCase tests NonNullElements.
*
* @author Luke
*
*/
public class NonNullElementsTest extends TestCase {
World w;
StationModel station1;
StationModel station2;
StationModel station3;
public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}
public static Test suite() {
TestSuite testSuite = new TestSuite(NonNullElementsTest.class);
return testSuite;
}
@Override
protected void setUp() {
w = new WorldImpl();
station1 = new StationModel(10, 20, "Station1", 4, 0);
station2 = new StationModel(15, 16, "Station2", 4, 1);
station3 = new StationModel(30, 50, "Station3", 4, 2);
w.addPlayer(MapFixtureFactory.TEST_PLAYER);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, station1);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, null);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, station2);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, null);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, null);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, station3);
}
public void testNext() {
WorldIterator wi = new NonNullElements(KEY.STATIONS, w,
MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(WorldIterator.BEFORE_FIRST, wi.getRowID());
assertEquals(WorldIterator.BEFORE_FIRST, wi.getIndex());
// Look at first station
boolean b = wi.next();
assertTrue(b);
int index = wi.getIndex();
assertEquals(0, index);
assertEquals(0, wi.getRowID());
assertEquals(station1, wi.getElement());
// Look at second station
assertTrue(wi.next());
assertEquals(2, wi.getIndex());
assertEquals(1, wi.getRowID());
assertEquals(station2, wi.getElement());
WorldIterator wi2 = new NonNullElements(SKEY.TRACK_RULES, w);
assertTrue(!wi2.next());
}
public void testGotoIndex() {
WorldIterator wi = new NonNullElements(KEY.STATIONS, w,
MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(WorldIterator.BEFORE_FIRST, wi.getRowID());
assertEquals(WorldIterator.BEFORE_FIRST, wi.getIndex());
wi.gotoIndex(2);
assertEquals(2, wi.getIndex());
assertEquals(1, wi.getRowID());
try {
wi.gotoIndex(100);
assertTrue(false);
} catch (NoSuchElementException e) {
}
}
}

WorldImplTest

Full name: jfreerails.world.top.WorldImplTest

Documentation

/**
* Junit test.
*
* @author Luke
*
*/

Source Code

/**
* Junit test.
*
* @author Luke
*
*/
public class WorldImplTest extends TestCase {
private final FreerailsSerializable fs = new TestState(1);
public void testGet() {
WorldImpl w = new WorldImpl();
w.add(SKEY.TERRAIN_TYPES, fs);
assertEquals(w.get(SKEY.TERRAIN_TYPES, 0), fs);
}
public void testConstructor() {
World w = new WorldImpl();
assertEquals("The width should be zero", 0, w.getMapWidth());
assertEquals("The height should be zero", 0, w.getMapHeight());
}
/**
* Tests that changing the object returned by defensiveCopy() does not alter
* the world object that was copied.
*/
public void testDefensiveCopy() {
World original;
World copy;
original = new WorldImpl();
copy = original.defensiveCopy();
assertNotSame("The copies should be different objects.", original, copy);
assertEquals("The copies should be logically equal.", original, copy);
copy.add(SKEY.TERRAIN_TYPES, fs);
assertFalse(original.equals(copy));
assertFalse(copy.equals(original));
assertEquals(1, copy.size(SKEY.TERRAIN_TYPES));
assertEquals(0, original.size(SKEY.TERRAIN_TYPES));
}
public void testEquals() {
World original;
World copy;
original = new WorldImpl();
copy = original.defensiveCopy();
Player player = new Player("Name", 0);
int index = copy.addPlayer(player);
assertEquals(index, 0);
assertFalse(copy.equals(original));
original.addPlayer(player);
assertEquals("The copies should be logically equal.", original, copy);
assertTrue(Utils.equalsBySerialization(original, copy));
Transaction t = new Receipt(new Money(100),
Transaction.Category.MISC_INCOME);
copy.addTransaction(player.getPrincipal(), t);
assertEquals(new Money(100), copy.getCurrentBalance(player
.getPrincipal()));
assertFalse(copy.equals(original));
}
public void testEquals2() {
World original;
World copy, copy2;
original = new WorldImpl();
copy = original.defensiveCopy();
copy2 = original.defensiveCopy();
// Test adding players.
Player a = new Player("Fred");
Player b = new Player("John");
original.addPlayer(a);
copy.addPlayer(b);
assertFalse(copy.equals(original));
copy.removeLastPlayer();
assertTrue(copy2.equals(copy));
copy.addPlayer(a);
assertTrue(copy.equals(original));
}
public void testActivityLists() {
World w = new WorldImpl();
Player player = new Player("Name", 0);
w.addPlayer(player);
FreerailsPrincipal principal = player.getPrincipal();
// Test adding activities.
assertEquals(0, w.size(principal));
Activity act = new TestActivity(30);
int actIndex = w.addActiveEntity(principal, act);
assertEquals(0, actIndex);
assertEquals(1, w.size(principal));
actIndex = w.addActiveEntity(principal, act);
assertEquals(1, actIndex);
assertEquals(2, w.size(principal));
// Then removing them.
Activity expected = new TestActivity(30);
assertEquals(expected, act);
Activity actual = w.removeLastActiveEntity(principal);
assertEquals(actual, expected);
assertEquals(1, w.size(principal));
}
public static class TestState implements FreerailsSerializable {
private static final long serialVersionUID = 5122023949873919060L;
public final int x;
public TestState(int x) {
this.x = x;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TestState))
return false;
final TestState testState = (TestState) o;
if (x != testState.x)
return false;
return true;
}
@Override
public int hashCode() {
return x;
}
}
public static class TestActivity implements Activity {
private static final long serialVersionUID = 1298936498785131183L;
private final double duration;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TestActivity))
return false;
final TestActivity testActivity = (TestActivity) o;
if (duration != testActivity.duration)
return false;
return true;
}
@Override
public int hashCode() {
return (int) duration;
}
public TestActivity(int duration) {
this.duration = duration;
}
public double duration() {
return duration;
}
public FreerailsSerializable getState(double dt) {
return new TestState((int) dt);
}
@Override
public String toString() {
return getClass().getName() + "{" + duration + "}";
}
}
public void testBoundsContain(){
World w = new WorldImpl();
assertFalse(w.boundsContain(1, 1));
assertFalse(w.boundsContain(0, 0));
assertFalse(w.boundsContain(-1, -1));
w = new WorldImpl(5, 10);
assertTrue(w.boundsContain(0, 0));
assertTrue(w.boundsContain(4, 9));
assertFalse(w.boundsContain(-1, -1));
assertFalse(w.boundsContain(5, 10));
}
public void testBankAccount(){
WorldImpl world = new WorldImpl();
Player p = new Player("Test", 0);
int playerID = world.addPlayer(p);
assertEquals(0, playerID);
FreerailsPrincipal fp = world.getPlayer(playerID).getPrincipal();
Transaction t = new AddItemTransaction(Category.BOND, 1, 2, new Money(100));
assertEquals(new Money(0), world.getCurrentBalance(fp));
world.addTransaction(fp, t);
assertEquals(1, world.getNumberOfTransactions(fp));
assertEquals(new Money(100), world.getCurrentBalance(fp));
Transaction t2 = world.getTransaction(fp, 0);
assertEquals(t, t2);
Transaction t3 = world.removeLastTransaction(fp);
assertEquals(t, t3);
assertEquals(new Money(0), world.getCurrentBalance(fp));
}
}

ItemsTransactionAggregatorTest

Full name: jfreerails.world.top.ItemsTransactionAggregatorTest

Documentation

/**
* Tests the ItemsTransactionAggregator class to ensure it correctly calculates the quantity
* of items based on added transactions.
*
* This test verifies that the aggregator returns the correct quantity after adding various
* AddItemTransaction instances, confirming its functionality.
*
* @see ItemsTransactionAggregator
* @see AddItemTransaction
* @see World
* @see Player
* @see FreerailsPrincipal
*/

Source Code

public class ItemsTransactionAggregatorTest extends TestCase {
public void test1(){
World w = new WorldImpl();
Player player = new Player("name", 0);
w.addPlayer(player);
FreerailsPrincipal fp = w.getPlayer(0).getPrincipal();
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(w, fp);
aggregator.setCategory(TRACK);
int quant = aggregator.calculateQuantity();
assertEquals(0, quant);
Transaction t = new AddItemTransaction(Category.TRACK, 10, 5 , new Money(100));
w.addTransaction(fp, t);
quant = aggregator.calculateQuantity();
assertEquals(5, quant);
t = new AddItemTransaction(Category.TRACK, 10, 11 , new Money(200));
w.addTransaction(fp, t);
}
}

Methods

JavaDocPlaceholder

Full name: jfreerails.world.JavaDocPlaceholder

Documentation

/**
* This class does nothing and is only here so that javadoc gets generated
* correctly.
*
* @author Luke
*
*/

Source Code

/**
* This class does nothing and is only here so that javadoc gets generated
* correctly.
*
* @author Luke
*
*/
public class JavaDocPlaceholder {
}

Methods

No methods found

Constants

Full name: jfreerails.world.Constants

Documentation

/**
* game constants
*
* @author Roland Spatzenegger
* @version $Revision 1.1$
*/

Source Code

/**
* game constants
*
* @author Roland Spatzenegger
* @version $Revision 1.1$
*/
public final class Constants {
/**
* size of a tile (height and width)
*/
public static final int TILE_SIZE = 30;
}

Methods

No methods found

CargoBundleTest

Full name: jfreerails.world.cargo.CargoBundleTest

Documentation

/**
* Test class for verifying the equality logic of the MutableCargoBundle and its Immutable counterpart.
* This class ensures that the equals method behaves correctly under various scenarios, including different cargo batches, quantities, and conversions to immutable versions.
*
* @author YourName
* @since 1.0
*
* @see MutableCargoBundle
* @see ImmutableCargoBundle
* @see CargoBatch
*/

Source Code

public class CargoBundleTest extends TestCase {
public void testEquals() {
MutableCargoBundle bundle1 = new MutableCargoBundle();
MutableCargoBundle bundle2 = new MutableCargoBundle();
CargoBatch batch1 = new CargoBatch(1, 2, 3, 4, 5);
CargoBatch batch2 = new CargoBatch(4, 2, 3, 4, 5);
int q1 = 10;
int q2 = 20;
bundle1.addCargo(batch1, q1);
bundle1.addCargo(batch2, q2);
assertBundlesNotEqual(bundle1, bundle2);
bundle2.addCargo(batch2, q2);
assertBundlesNotEqual(bundle1, bundle2);
bundle2.addCargo(batch1, q1);
assertBundlesEqual(bundle1, bundle2);
}
private void assertBundlesEqual(MutableCargoBundle a, MutableCargoBundle b) {
assertEquals(a, b);
assertEquals(a, a);
assertEquals(b, a);
ImmutableCargoBundle immA = a.toImmutableCargoBundle();
assertEquals(immA, immA);
assertEquals(immA, b);
ImmutableCargoBundle immB = b.toImmutableCargoBundle();
assertEquals(immA, immB);
Serializable cloneA = Utils.cloneBySerialisation(immA);
Serializable cloneB = Utils.cloneBySerialisation(immB);
assertEquals(cloneA, cloneB);
assertEquals(a, immB);
}
private void assertBundlesNotEqual(MutableCargoBundle a,
MutableCargoBundle b) {
assertFalse(a.equals(b));
assertFalse(b.equals(a));
assertFalse(a.toImmutableCargoBundle().equals(b));
assertFalse(a.toImmutableCargoBundle().equals(
b.toImmutableCargoBundle()));
assertFalse(a.equals(b.toImmutableCargoBundle()));
}
}

CargoTypeTest

Full name: jfreerails.world.cargo.CargoTypeTest

Documentation

/**
* JUnit test for CargoType.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test for CargoType.
*
* @author Luke
*
*/
public class CargoTypeTest extends TestCase {
public void testCargoType() {
// Test that invalid categories get rejected.
try {
new CargoType(10, "Test", Categories
.getCategory("Non valid category"));
fail();
} catch (Exception e) {
}
try {
new CargoType(10, "Test", Categories.Mail);
} catch (Exception e) {
fail();
}
}
}

Methods

ReadOnlyWorld

Full name: jfreerails.world.top.ReadOnlyWorld

Documentation

/**
* <p>
* This interface defines a unified set of methods to access the elements that
* make up the game world. The game world is composed of the following
* specific-purpose collections into which one can put game world elements.
* </p>
* <ul>
* A list of players.
* </ul>
* <ul>
* A 2D grid - the map.
* </ul>
* <ul>
* A series of lists that are accessible using the keys defined in {@link SKEY}
* </ul>
* <ul>
* Another series of lists indexed by player and accessible using the keys
* defined in {@link KEY}
* </ul>
* <ul>
* A collection items accessible using the keys defined in {@link ITEM}
* </ul>
* <ul>
* A list of financial transactions for each of the players
* </ul>
* <p>
* Example: the following code gets player1's train #5.
* </p>
* <p>
* <CODE>TrainModel t = (TrainModel)world.get(KEY.TRAINS, 5, player1);</CODE>
* </p>
* <p>
* The motivation for accessing lists using keys is that one does not need to
* add a new class or change the interface of the World class when a new list is
* added. Instead one can just add a new entry to the class KEY.
* </p>
* <p>
* Code that loops through lists should handle null values gracefully
* </p>
*
*
* @author Luke
* @author Rob
*/

Source Code

/**
* <p>
* This interface defines a unified set of methods to access the elements that
* make up the game world. The game world is composed of the following
* specific-purpose collections into which one can put game world elements.
* </p>
* <ul>
* A list of players.
* </ul>
* <ul>
* A 2D grid - the map.
* </ul>
* <ul>
* A series of lists that are accessible using the keys defined in {@link SKEY}
* </ul>
* <ul>
* Another series of lists indexed by player and accessible using the keys
* defined in {@link KEY}
* </ul>
* <ul>
* A collection items accessible using the keys defined in {@link ITEM}
* </ul>
* <ul>
* A list of financial transactions for each of the players
* </ul>
* <p>
* Example: the following code gets player1's train #5.
* </p>
* <p>
* <CODE>TrainModel t = (TrainModel)world.get(KEY.TRAINS, 5, player1);</CODE>
* </p>
* <p>
* The motivation for accessing lists using keys is that one does not need to
* add a new class or change the interface of the World class when a new list is
* added. Instead one can just add a new entry to the class KEY.
* </p>
* <p>
* Code that loops through lists should handle null values gracefully
* </p>
*
*
* @author Luke
* @author Rob
*/
public interface ReadOnlyWorld extends FreerailsMutableSerializable {
boolean boundsContain(int x, int y);
boolean boundsContain(FreerailsPrincipal p, KEY k, int index);
boolean boundsContain(SKEY k, int index);
GameTime currentTime();
/**
* Returns the element mapped to the specified item.
*/
FreerailsSerializable get(ITEM item);
/**
* Returns the element at the specified position in the specified list.
*/
FreerailsSerializable get(FreerailsPrincipal p, KEY key, int index);
/**
* Returns the element at the specified position in the specified list.
*/
FreerailsSerializable get(SKEY key, int index);
ActivityIterator getActivities(FreerailsPrincipal p, int index);
Money getCurrentBalance(FreerailsPrincipal p);
int getID(FreerailsPrincipal p);
/**
* Returns the height of the map in tiles.
*/
int getMapHeight();
/**
* Returns the width of the map in tiles.
*/
int getMapWidth();
int getNumberOfPlayers();
int getNumberOfTransactions(FreerailsPrincipal p);
int getNumberOfActiveEntities(FreerailsPrincipal p);
Player getPlayer(int i);
/**
* Returns the tile at the specified position on the map.
*/
FreerailsSerializable getTile(int x, int y);
Transaction getTransaction(FreerailsPrincipal p, int i);
GameTime getTransactionTimeStamp(FreerailsPrincipal p, int i);
public Pair<Transaction, GameTime> getTransactionAndTimeStamp(
FreerailsPrincipal p, int i);
boolean isPlayer(FreerailsPrincipal p);
/**
* Returns the number of elements in the specified list.
*/
int size(FreerailsPrincipal p, KEY key);
/**
* Returns the number of elements in the specified list.
*/
int size(SKEY key);
/**
* Returns number of active entities belonging to the specified principal.
*/
int size(FreerailsPrincipal p);
}

ITEM

Full name: jfreerails.world.top.ITEM

Documentation

/**
* <p>
* This class provides a set of keys to access the items of which there can only
* be one instance in the game world in the game world (for example, the current
* time).
* </P>
*
* <p>
* It implements the typesafe enum pattern (see Bloch, <I>Effective Java</I>
* item 21)
* </p>
*
* @author Luke
*/

Source Code

/**
* <p>
* This class provides a set of keys to access the items of which there can only
* be one instance in the game world in the game world (for example, the current
* time).
* </P>
*
* <p>
* It implements the typesafe enum pattern (see Bloch, <I>Effective Java</I>
* item 21)
* </p>
*
* @author Luke
*/
@jfreerails.util.InstanceControlled
public class ITEM implements FreerailsSerializable {
private static final long serialVersionUID = 3257846593180151859L;
/** Maps key numbers to KEYs. */
private static final ITEM[] keys = new ITEM[getNumberOfKeys()];
// START OF KEYS
public static final ITEM CALENDAR = new ITEM();
public static final ITEM GAME_RULES = new ITEM();
public static final ITEM GAME_SPEED = new ITEM();
public static final ITEM ECONOMIC_CLIMATE = new ITEM();
// END OF KEYS
private static int numberOfKeys = 0;
private final int keyNumber;
private ITEM() {
this.keyNumber = numberOfKeys;
keys[keyNumber] = this;
numberOfKeys++;
}
static int getNumberOfKeys() {
return ITEM.class.getFields().length;
}
int getKeyID() {
return keyNumber;
}
private Object readResolve() throws ObjectStreamException {
return keys[this.keyNumber];
}
@Override
public String toString() {
return Utils.findConstantFieldName(this);
}
}

NonNullElements

Full name: jfreerails.world.top.NonNullElements

Documentation

/**
* Iterates over one of the lists on the world object only returning non null
* elements.
*
* @author Luke
*
*/

Source Code

/**
* Iterates over one of the lists on the world object only returning non null
* elements.
*
* @author Luke
*
*/
public class NonNullElements implements WorldIterator {
private final KEY key;
private final SKEY skey;
private final ReadOnlyWorld w;
private final FreerailsPrincipal principal;
private int index = BEFORE_FIRST;
private int row = BEFORE_FIRST;
private int size = -1;
public NonNullElements(SKEY k, ReadOnlyWorld world) {
if (null == k) {
throw new NullPointerException();
}
if (null == world) {
throw new NullPointerException();
}
key = null;
principal = null;
skey = k;
w = world;
}
public NonNullElements(KEY k, ReadOnlyWorld world, FreerailsPrincipal p) {
key = k;
w = world;
principal = p;
skey = null;
if (null == k) {
throw new NullPointerException();
}
if (null == world) {
throw new NullPointerException();
}
if (null == p) {
throw new NullPointerException();
}
}
public boolean next() {
int nextIndex = index; // this is used to look ahead.
do {
nextIndex++;
if (nextIndex >= listSize()) {
return false;
}
} while (!testCondition(nextIndex));
row++;
index = nextIndex;
return true;
}
public void reset() {
index = -1;
row = -1;
size = -1;
}
public FreerailsSerializable getElement() {
return listGet(index);
}
private FreerailsSerializable listGet(int i) {
if (null == this.skey) {
return w.get(principal, key, i);
}
return w.get(skey, i);
}
private int listSize() {
if (null == this.skey) {
return w.size(principal, key);
}
return w.size(this.skey);
}
public int getIndex() {
return index;
}
public int getRowID() {
return row;
}
public int size() {
if (-1 == size) { // lazy loading, if we have already calculated the
// size don't do it again.
int tempSize = 0;
for (int i = 0; i < listSize(); i++) {
if (null != listGet(i)) {
tempSize++;
}
}
size = tempSize;
}
return size;
}
public boolean previous() {
int previousIndex = index; // this is used to look back.
do {
previousIndex--;
if (previousIndex < 0) {
return false;
}
} while (!testCondition(previousIndex));
row--;
index = previousIndex;
return true;
}
/** Moves the cursor to the specified index. */
public void gotoIndex(int i) {
int newRow = -1;
for (int j = 0; j < listSize(); j++) {
if (testCondition(j)) {
newRow++;
if (i == j) {
reset();
this.index = i;
this.row = newRow;
return;
}
}
}
throw new NoSuchElementException("Index:" + String.valueOf(i)
+ " Size:" + listSize() + " Row:" + newRow);
}
protected boolean testCondition(int i) {
return null != listGet(i);
}
public int getNaturalNumber() {
return getRowID() + 1;
}
public void gotoRow(int newRow) {
if (row == newRow) {
return;
}
if (row < newRow) {
while (row != newRow) {
next();
}
} else {
while (row != newRow) {
previous();
}
}
return;
}
public static int row2index(ReadOnlyWorld w, KEY key, FreerailsPrincipal p,
int row) {
int count = 0;
for (int i = 0; i < w.size(p, key); i++) {
if (w.get(p, key, i) != null) {
if (count == row) {
return i;
}
count++;
}
}
throw new NoSuchElementException(String.valueOf(row));
}
}

MapFixtureFactory

Full name: jfreerails.world.top.MapFixtureFactory

Documentation

/**
* This class is used to generate fixtures for Junit tests.
*
* @author Luke
*
*/

Source Code

/**
* This class is used to generate fixtures for Junit tests.
*
* @author Luke
*
*/
public class MapFixtureFactory {
/** Only subclasses should use these constants. */
public static final Player TEST_PLAYER = new Player("test player", 0);
public static final FreerailsPrincipal TEST_PRINCIPAL = TEST_PLAYER
.getPrincipal();
/**
* Returns a world object with a map of the specified size with the terrain
* and cargo types setup.
*/
public static World getWorld(int w, int h) {
FreerailsTile tile = FreerailsTile.getInstance(0);
World world = new WorldImpl(w, h);
generateTerrainTypesList(world);
generateCargoTypesList(world);
for (int x = 0; x < w; x++) {
for (int y = 0; y < w; y++) {
world.setTile(x, y, tile);
}
}
return world;
}
public static void generateTrackRuleList(World world) {
TrackRule[] trackRulesArray = new TrackRule[3];
TrackRuleProperties[] trackRuleProperties = new TrackRuleProperties[3];
LegalTrackConfigurations[] legalTrackConfigurations = new LegalTrackConfigurations[3];
LegalTrackPlacement[] legalTrackPlacement = new LegalTrackPlacement[3];
HashSet<TerrainType.Category> cannotBuildOnTheseTerrainTypes = new HashSet<TerrainType.Category>();
cannotBuildOnTheseTerrainTypes.add(TerrainType.Category.Ocean);
// 1st track type..
String[] trackTemplates0 = { "000010000", "010010000", "010010010",
"100111000", "001111000", "010110000", "100110000", "100011000" };
legalTrackConfigurations[0] = new LegalTrackConfigurations(-1,
trackTemplates0);
trackRuleProperties[0] = new TrackRuleProperties(1, false, "type0",
TrackRule.TrackCategories.track, 0, 0, 10, 0);
legalTrackPlacement[0] = new LegalTrackPlacement(
cannotBuildOnTheseTerrainTypes,
LegalTrackPlacement.PlacementRule.ANYWHERE_EXCEPT_ON_THESE);
trackRulesArray[0] = new TrackRuleImpl(trackRuleProperties[0],
legalTrackConfigurations[0], legalTrackPlacement[0]);
// 2nd track type..
String[] trackTemplates1 = { "000010000", "010010000", "010010010" };
legalTrackConfigurations[1] = new LegalTrackConfigurations(-1,
trackTemplates1);
trackRuleProperties[1] = new TrackRuleProperties(2, false, "type1",
TrackRule.TrackCategories.track, 0, 0, 20, 0);
legalTrackPlacement[1] = new LegalTrackPlacement(
cannotBuildOnTheseTerrainTypes,
LegalTrackPlacement.PlacementRule.ANYWHERE_EXCEPT_ON_THESE);
trackRulesArray[1] = new TrackRuleImpl(trackRuleProperties[1],
legalTrackConfigurations[1], legalTrackPlacement[1]);
// 3rd track type..
trackRuleProperties[2] = new TrackRuleProperties(3, false, "type2",
TrackRule.TrackCategories.track, 0, 0, 30, 0);
String[] trackTemplates2 = { "000010000" };
legalTrackConfigurations[2] = new LegalTrackConfigurations(-1,
trackTemplates2);
legalTrackPlacement[2] = new LegalTrackPlacement(
cannotBuildOnTheseTerrainTypes,
LegalTrackPlacement.PlacementRule.ANYWHERE_EXCEPT_ON_THESE);
trackRulesArray[2] = new TrackRuleImpl(trackRuleProperties[2],
legalTrackConfigurations[2], legalTrackPlacement[2]);
// Add track rules to world
for (int i = 0; i < trackRulesArray.length; i++) {
world.add(SKEY.TRACK_RULES, trackRulesArray[i]);
}
// Add the terrain types if necessary.
if (world.size(SKEY.TERRAIN_TYPES) == 0) {
generateTerrainTypesList(world);
}
}
/** Adds hard coded cargo types. */
public static void generateCargoTypesList(World world) {
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Mail", Categories.Mail));
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Passengers",
Categories.Passengers));
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Goods",
Categories.Fast_Freight));
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Steel",
Categories.Slow_Freight));
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Coal",
Categories.Bulk_Freight));
}
/** Adds hard coded terrain types. */
private static void generateTerrainTypesList(World world) {
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Country, "Grassland"));
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Urban, "City"));
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Resource, "Mine"));
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Industry, "Factory"));
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Ocean, "Ocean"));
}
}

WorldMapListener

Full name: jfreerails.world.top.WorldMapListener

Documentation

/**
* Classes that need to be notified of changes to the map on the world object
* should implement this interface.
*
* @author Luke Lindsay
*
*
*/

Source Code

/**
* Classes that need to be notified of changes to the map on the world object
* should implement this interface.
*
* @author Luke Lindsay
*
*
*/
public interface WorldMapListener {
/**
* Called when tiles have changed.
*
* @param tilesChanged
* rectangle containing the tiles that have change; all the
* points contained by the rectangle must be within the map's
* bounds.
*/
void tilesChanged(Rectangle tilesChanged);
}

Methods

World

Full name: jfreerails.world.top.World

Documentation

/**
* <p>
* This class implements methods which can be used to alter the world. Notice
* that in contrast to, say, <CODE>java.util.List</CODE> there is no remove()
* method that shifts any subsequent elements to the left (subtracts one from
* their indices). This means that an elements' position in a list can be used
* as an address space independent way to reference the element. If you want to
* remove an element from a list, you should set it to null, e.g.
* </p>
* <p>
* <CODE>world.set(KEY.TRAINS, 5, null, player);</CODE>
* </P>
* <p>
* Code that loops through lists should handle null values gracefully
* </p>
*
* @author Luke
* @author rob
*/

Source Code

/**
* <p>
* This class implements methods which can be used to alter the world. Notice
* that in contrast to, say, <CODE>java.util.List</CODE> there is no remove()
* method that shifts any subsequent elements to the left (subtracts one from
* their indices). This means that an elements' position in a list can be used
* as an address space independent way to reference the element. If you want to
* remove an element from a list, you should set it to null, e.g.
* </p>
* <p>
* <CODE>world.set(KEY.TRAINS, 5, null, player);</CODE>
* </P>
* <p>
* Code that loops through lists should handle null values gracefully
* </p>
*
* @author Luke
* @author rob
*/
public interface World extends ReadOnlyWorld {
int addActiveEntity(FreerailsPrincipal principal, Activity element);
void add(FreerailsPrincipal principal, int index, Activity element);
/**
* Appends the specified element to the end of the specified list and returns
* the index that can be used to retrieve it.
*/
int add(FreerailsPrincipal principal, KEY key, FreerailsSerializable element);
/**
* Appends the specified element to the end of the specified list and returns
* the index that can be used to retrieve it.
*
*/
int add(SKEY key, FreerailsSerializable element);
int addPlayer(Player player);
/**
* Adds the specified transaction to the specified principal's bank account.
*/
void addTransaction(FreerailsPrincipal p, Transaction t);
/**
* Returns a copy of this world object - making changes to this copy will
* not change this object.
*/
World defensiveCopy();
Activity removeLastActiveEntity(FreerailsPrincipal principal);
Activity removeLastActivity(FreerailsPrincipal principal, int index);
/**
* Removes the last element from the specified list.
*/
FreerailsSerializable removeLast(FreerailsPrincipal principal, KEY key);
/**
* Removes the last element from the specified list.
*
*/
FreerailsSerializable removeLast(SKEY key);
/**
* Removes and returns the last transaction added the the specified
* principal's bank account. This method is only here so that moves that add
* transactions can be undone.
*/
Transaction removeLastTransaction(FreerailsPrincipal p);
Player removeLastPlayer();
/**
* Replaces the element mapped to the specified item with the specified
* element.
*
*/
void set(ITEM item, FreerailsSerializable element);
/**
* Replaces the element at the specified position in the specified list with
* the specified element.
*/
void set(FreerailsPrincipal principal, KEY key, int index,
FreerailsSerializable element);
/**
* Replaces the element at the specified position in the specified list with
* the specified element.
*
*/
void set(SKEY key, int index, FreerailsSerializable element);
/**
* Replaces the tile at the specified position on the map with the specified
* tile.
*
*/
void setTile(int x, int y, FreerailsSerializable tile);
void setTime(GameTime t);
}

WorldDiffs

Full name: jfreerails.world.top.WorldDiffs

Documentation

/**
* An implementation of World that only stores differences relative to an
* underlying world object. Below is some stylised code showing what this class
* does. The <code>key</code> object could be a location on the map, a
* position in a list etc. <code><pre>
* HashMap underlyingWorldObject;
*
* HashMap differences;
*
* public void put(Object key, Object value) {
* if (underlyingWorldObject.get(key).equals(value)) {
* if (differences.containsKey(key)) {
* differences.remove(key);
* }
* } else {
* differences.put(key, value);
* }
* }
*
* public Object get(Object key) {
* if (differences.containsKey(key)) {
* return differences.get(key);
* } else {
* return underlyingWorldObject.get(key);
* }
* }
* </code></pre>
*
* The advantages of using an instance of this class instead of a copy of the
* world object are:
* <ol>
* <li> Uses less memory.</li>
* <li> Lets you pinpoint where differences on the map are, so you don't need to
* check every tile. </li>
* </ol>
*
*
* @author Luke
* @version 2
*
*/

Source Code

/**
* An implementation of World that only stores differences relative to an
* underlying world object. Below is some stylised code showing what this class
* does. The <code>key</code> object could be a location on the map, a
* position in a list etc. <code><pre>
* HashMap underlyingWorldObject;
*
* HashMap differences;
*
* public void put(Object key, Object value) {
* if (underlyingWorldObject.get(key).equals(value)) {
* if (differences.containsKey(key)) {
* differences.remove(key);
* }
* } else {
* differences.put(key, value);
* }
* }
*
* public Object get(Object key) {
* if (differences.containsKey(key)) {
* return differences.get(key);
* } else {
* return underlyingWorldObject.get(key);
* }
* }
* </code></pre>
*
* The advantages of using an instance of this class instead of a copy of the
* world object are:
* <ol>
* <li> Uses less memory.</li>
* <li> Lets you pinpoint where differences on the map are, so you don't need to
* check every tile. </li>
* </ol>
*
*
* @author Luke
* @version 2
*
*/
public class WorldDiffs extends WorldImpl {
public enum LISTID {
ACTIVITY_LISTS, BANK_ACCOUNTS, CURRENT_BALANCE, ITEMS, LISTS, PLAYERS, SHARED_LISTS
}
private static final long serialVersionUID = -5993786533926919956L;
private final SortedMap<ListKey, Object> listDiff;
/** Stores the differences on the map, ImPoint are used as keys. */
private final HashMap<ImPoint, Object> mapDiff;
private final WorldImpl underlying;
public WorldDiffs(ReadOnlyWorld row){
listDiff = new TreeMap<ListKey, Object>();
mapDiff = new HashMap<ImPoint, Object>();
//Bit of a hack but it's not clear there is a better way, LL
underlying = (WorldImpl)row;
activityLists = new List3DDiff<ActivityAndTime>(listDiff,
underlying.activityLists, LISTID.ACTIVITY_LISTS);
bankAccounts = new List2DDiff<TransactionAndTimeStamp>(listDiff,
underlying.bankAccounts, LISTID.BANK_ACCOUNTS);
currentBalance = new List1DDiff<Money>(listDiff,
underlying.currentBalance, LISTID.CURRENT_BALANCE);
items = new List1DDiff<FreerailsSerializable>(listDiff,
underlying.items, LISTID.ITEMS);
lists = new List3DDiff<FreerailsSerializable>(listDiff,
underlying.lists, LISTID.LISTS);
players = new List1DDiff<Player>(listDiff, underlying.players,
LISTID.PLAYERS);
sharedLists = new List2DDiff<FreerailsSerializable>(listDiff,
underlying.sharedLists, LISTID.SHARED_LISTS);
time = underlying.time;
}
/**
* The iterator returns instances of java.awt.Point that store the
* coordinates of tiles that are different to the underlying world object.
*/
public Iterator<ImPoint> getMapDiffs() {
return mapDiff.keySet().iterator();
}
public Iterator<ListKey> getListDiffs() {
return listDiff.keySet().iterator();
}
public Object getDiff(ListKey key){
return listDiff.get(key);
}
@Override
public int getMapHeight() {
return underlying.getMapHeight();
}
@Override
public int getMapWidth() {
return underlying.getMapWidth();
}
@Override
public FreerailsSerializable getTile(int x, int y) {
ImPoint p = new ImPoint(x, y);
if (this.mapDiff.containsKey(p)) {
return (FreerailsSerializable) this.mapDiff.get(p);
}
return underlying.getTile(x, y);
}
/** Used by unit tests. */
public int numberOfMapDifferences() {
return this.mapDiff.size();
}
/** Used by unit tests. */
public int listDiffs() {
return listDiff.size();
}
/**
* After this method returns, all differences are cleared and calls to
* methods on this object should produce the same results as calls the the
* corresponding methods on the underlying world object.
*/
public void reset() {
time = underlying.currentTime();
mapDiff.clear();
listDiff.clear();
}
@Override
public void setTile(int x, int y, FreerailsSerializable tile) {
ImPoint p = new ImPoint(x, y);
if (Utils.equal(underlying.getTile(x, y), tile)) {
if (this.mapDiff.containsKey(p)) {
this.mapDiff.remove(p);
return;
}
} else {
this.mapDiff.put(p, tile);
}
}
public boolean isDifferent(){
return (mapDiff.size() != 0) || (listDiff.size() != 0);
}
public ReadOnlyWorld getUnderlying() {
return underlying;
}
}

ItemsTransactionAggregator

Full name: jfreerails.world.top.ItemsTransactionAggregator

Documentation

/**
* Adds up the number of assets.
*
* @author Luke
*
*/

Source Code

/**
* Adds up the number of assets.
*
* @author Luke
*
*/
public class ItemsTransactionAggregator extends TransactionAggregator {
public static final int ANY_VALUE = Integer.MIN_VALUE;
private int type = ANY_VALUE;
private Transaction.Category category = null;
private int[] quantities;
private int quantityRunningTotal;
/**
* Stores the quantities and monetary values of a series of items.
*
* @author Luke
*
*/
public static class QuantitiesAndValues {
public int[] quantities;
public Money[] values;
}
public ItemsTransactionAggregator(ReadOnlyWorld w,
FreerailsPrincipal principal) {
super(w, principal);
}
/**
* Returns true if the transaction with the specified ID has an acceptable
* type and category.
*/
@Override
protected boolean condition(int transactionID) {
Transaction t = w.getTransaction(principal, transactionID);
if (!(t instanceof AddItemTransaction)) {
return false;
}
AddItemTransaction addItemTransaction = (AddItemTransaction) t;
boolean isTypeAcceptable = (type == ANY_VALUE)
|| (type == addItemTransaction.getType());
boolean isCategoryAcceptable = (category == null)
|| (category == addItemTransaction.getCategory());
return isCategoryAcceptable && isTypeAcceptable;
}
public int calculateQuantity() {
QuantitiesAndValues qnv = calculateQuantitiesAndValues();
return qnv.quantities[0];
}
public QuantitiesAndValues calculateQuantitiesAndValues() {
QuantitiesAndValues returnValue = new QuantitiesAndValues();
returnValue.values = super.calculateValues();
returnValue.quantities = this.quantities;
return returnValue;
}
@Override
protected void incrementRunningTotal(int transactionID) {
super.incrementRunningTotal(transactionID);
Transaction t = w.getTransaction(principal, transactionID);
AddItemTransaction addItemTransaction = (AddItemTransaction) t;
quantityRunningTotal += addItemTransaction.getQuantity();
}
@Override
protected void setTotalsArrayLength(int length) {
super.setTotalsArrayLength(length);
quantities = new int[length];
quantityRunningTotal = 0;
}
@Override
protected void storeRunningTotal(int timeIndex) {
/*
* Note, a negative sign since we are totalling the value of assets not
* their impact on the operating funds.
*/
monetaryTotals[timeIndex] = new Money(-runningTotal);
quantities[timeIndex] = quantityRunningTotal;
}
public Transaction.Category getCategory() {
return category;
}
public void setCategory(Transaction.Category category) {
this.category = category;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}

WorldIterator

Full name: jfreerails.world.top.WorldIterator

Documentation

/**
* This interface lets the caller access the results of a search in the
* gameworld. It is similar in concept to <code>java.sql.ResultSet</code>.
*
* @author Luke
*
*/

Source Code

/**
* This interface lets the caller access the results of a search in the
* gameworld. It is similar in concept to <code>java.sql.ResultSet</code>.
*
* @author Luke
*
*/
public interface WorldIterator {
public static final int BEFORE_FIRST = -1;
/**
* Moves the cursor down one row from its current position.
*/
boolean next();
/**
* Moves the cursor up one row from its current position.
*/
boolean previous();
/**
* Moves the cursor to before the first element and updates any cached
* values.
*/
void reset();
/** Returns the element the cursor is pointing to. */
FreerailsSerializable getElement();
/**
* Returns the index of the element the cursor is pointing to. The value
* returned is index you would need to use in
* <code>World.get(KEY key, int index)</code> to retrieve the same element
* as is returned by <code>getElement()</code>
*/
int getIndex();
/**
* Returns the number of the row where the cursor is (the first row is 0).
*/
int getRowID();
/** Returns the number of rows. */
int size();
/**
* Moves the cursor to the specified index.
*
* @throws NoSuchElementException
* if index out of range
*/
void gotoIndex(int i);
/** Moves the cursor to the specified index. */
void gotoRow(int row);
/**
* Returns the number of the row where the cursor is (the first row is 1).
*/
int getNaturalNumber();
}

WorldImpl

Full name: jfreerails.world.top.WorldImpl

Documentation

/**
* An implementation of World that uses standard java.util collections
* internally.
*
* @author Luke
*
*/

Source Code

/**
* An implementation of World that uses standard java.util collections
* internally.
*
* @author Luke
*
*/
public class WorldImpl implements World {
public class ActivityIteratorImpl implements ActivityIterator {
public int activityIndex = 0;
private ActivityAndTime ant;
private List<ActivityAndTime> currentList;
public int size;
public ActivityIteratorImpl(int playerIndex, int index) {
currentList = activityLists.get(playerIndex, index);
size = currentList.size();
ant = currentList.get(activityIndex);
}
public double absolute2relativeTime(double t) {
double dt = t - ant.startTime;
dt = Math.min(dt, ant.act.duration());
return dt;
}
public Activity getActivity() {
return ant.act;
}
public double getDuration() {
return ant.act.duration();
}
public double getFinishTime() {
double ticks = ant.startTime + ant.act.duration();
return ticks;
}
public double getStartTime() {
return ant.startTime;
}
public FreerailsSerializable getState(double t) {
double dt = absolute2relativeTime(t);
return ant.act.getState(dt);
}
public boolean hasNext() {
return (activityIndex + 1) < size;
}
public void nextActivity() {
if (!hasNext()) {
throw new NoSuchElementException();
}
activityIndex++;
ant = currentList.get(activityIndex);
}
public void gotoLastActivity() {
activityIndex = size - 1;
ant = currentList.get(activityIndex);
}
public boolean hasPrevious() {
return activityIndex >= 1;
}
public void previousActivity() throws NoSuchElementException {
if (!hasPrevious()) {
throw new NoSuchElementException();
}
activityIndex--;
ant = currentList.get(activityIndex);
}
}
public static class ActivityAndTime implements FreerailsSerializable {
private static final long serialVersionUID = -5149207279086814649L;
public final Activity act;
public final double startTime;
ActivityAndTime(Activity act, double time) {
this.act = act;
startTime = time;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ActivityAndTime))
return false;
final ActivityAndTime activityAndTime = (ActivityAndTime) o;
if (!act.equals(activityAndTime.act))
return false;
if (startTime != activityAndTime.startTime)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = act.hashCode();
result = 29 * result + (int) startTime;
return result;
}
}
private static final long serialVersionUID = 3544393612684505393L;
/** A 3D list: D1 is player, D2 is train id, D3 is train position. */
List3D<ActivityAndTime> activityLists;
/** A 2D list: D1 is player, D2 is transaction. */
List2D<TransactionAndTimeStamp> bankAccounts;
List1D<Money> currentBalance;
List1D<FreerailsSerializable> items;
/** A 3D list: D1 is player, D2 is type, D3 is element. */
List3D<FreerailsSerializable> lists;
FreerailsSerializable[][] map;
List1D<Player> players;
/** A 2D list: D1 is type, D2 is element. */
List2D<FreerailsSerializable> sharedLists;
GameTime time = GameTime.BIG_BANG;
public WorldImpl() {
this(0, 0);
}
public WorldImpl(int mapWidth, int mapHeight) {
activityLists = new List3DImpl<ActivityAndTime>(0, 0);
bankAccounts = new List2DImpl<TransactionAndTimeStamp>(0);
currentBalance = new List1DImpl<Money>();
items = new List1DImpl<FreerailsSerializable>(ITEM.getNumberOfKeys());
lists = new List3DImpl<FreerailsSerializable>(0, KEY.getNumberOfKeys());
players = new List1DImpl<Player>();
sharedLists = new List2DImpl<FreerailsSerializable>(SKEY
.getNumberOfKeys());
time = GameTime.BIG_BANG;
setupItems();
setupMap(mapWidth, mapHeight);
}
@SuppressWarnings("unchecked")
public void add(FreerailsPrincipal p, int index, Activity element) {
int playerIndex = p.getWorldIndex();
int lastID = activityLists.sizeD3(playerIndex, index) - 1;
ActivityAndTime last = activityLists.get(playerIndex, index, lastID);
double duration = last.act.duration();
double lastFinishTime = last.startTime + duration;
double thisStartTime = Math.max(lastFinishTime, currentTime()
.getTicks());
ActivityAndTime ant = new ActivityAndTime(element, thisStartTime);
activityLists.addD3(playerIndex, index, ant);
}
public int add(FreerailsPrincipal p, KEY key, FreerailsSerializable element) {
int playerIndex = p.getWorldIndex();
return lists.addD3(playerIndex, key.getKeyID(), element);
}
public int add(SKEY key, FreerailsSerializable element) {
return sharedLists.addD2(key.getKeyID(), element);
}
public int addActiveEntity(FreerailsPrincipal p, Activity element) {
int playerIndex = p.getWorldIndex();
int index = activityLists.addD2(playerIndex);
ActivityAndTime ant = new ActivityAndTime(element, currentTime()
.getTicks());
activityLists.addD3(playerIndex, index, ant);
return index;
}
/**
* @param player
* Player to add
* @return index of the player
*/
public int addPlayer(Player player) {
if (null == player) {
throw new NullPointerException();
}
int index = players.add(player);
bankAccounts.addD1();
currentBalance.add(new Money(0));
lists.addD1();
for (int i = 0; i < KEY.getNumberOfKeys(); i++) {
lists.addD2(index);
}
activityLists.addD1();
return index;
}
public void addTransaction(FreerailsPrincipal p, Transaction t) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = new TransactionAndTimeStamp(t, time);
bankAccounts.addD2(playerIndex, tats);
Money oldBalance = currentBalance.get(playerIndex);
Money newBalance = new Money(t.deltaCash().getAmount()
+ oldBalance.getAmount());
currentBalance.set(playerIndex, newBalance);
}
public boolean boundsContain(FreerailsPrincipal p, KEY k, int index) {
if (!isPlayer(p)) {
return false;
} else if (index >= 0 && index < this.size(p, k)) {
return true;
} else {
return false;
}
}
public boolean boundsContain(int x, int y) {
if (x >= 0 && x < getMapWidth() && y >= 0 && y < getMapHeight()) {
return true;
}
return false;
}
public boolean boundsContain(SKEY k, int index) {
return (index >= 0 && index < this.size(k));
}
public GameTime currentTime() {
return time;
}
public World defensiveCopy() {
return (World) Utils.cloneBySerialisation(this);
}
@Override
public boolean equals(Object o) {
if (o instanceof WorldImpl) {
WorldImpl test = (WorldImpl) o;
// Compare players
int numberOfPlayers = getNumberOfPlayers();
if (numberOfPlayers != test.getNumberOfPlayers())
return false;
for (int i = 0; i < numberOfPlayers; i++) {
if (!getPlayer(i).equals(test.getPlayer(i)))
return false;
}
// Compare lists
if (!lists.equals(test.lists)) {
return false;
}
if (!sharedLists.equals(test.sharedLists)) {
return false;
}
if (!activityLists.equals(test.activityLists)) {
return false;
}
if (!items.equals(test.items)) {
return false;
}
if (!bankAccounts.equals(test.bankAccounts)) {
return false;
}
// Compare maps
if ((this.getMapWidth() != test.getMapWidth())
|| (this.getMapHeight() != test.getMapHeight())) {
return false;
}
for (int x = 0; x < this.getMapWidth(); x++) {
for (int y = 0; y < this.getMapHeight(); y++) {
if (!getTile(x, y).equals(test.getTile(x, y))) {
return false;
}
}
}
// phew!
return true;
}
return false;
}
public FreerailsSerializable get(FreerailsPrincipal p, KEY key, int index) {
int playerIndex = p.getWorldIndex();
return lists.get(playerIndex, key.getKeyID(), index);
}
public FreerailsSerializable get(ITEM item) {
return items.get(item.getKeyID());
}
public FreerailsSerializable get(SKEY key, int index) {
return sharedLists.get(key.getKeyID(), index);
}
public ActivityIterator getActivities(final FreerailsPrincipal p, int index) {
final int playerIndex = p.getWorldIndex();
return new ActivityIteratorImpl(playerIndex, index);
}
public Money getCurrentBalance(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
return currentBalance.get(playerIndex);
}
public int getID(FreerailsPrincipal p) {
return p.getWorldIndex();
}
public int getMapHeight() {
if (map.length == 0) {
// When the map size is 0*0 we get a
// java.lang.ArrayIndexOutOfBoundsException: 0
// if we don't have the check above.
return 0;
}
return map[0].length;
}
public int getMapWidth() {
return map.length;
}
public int getNumberOfPlayers() {
return players.size();
}
public int getNumberOfTransactions(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
return bankAccounts.sizeD2(playerIndex);
}
public Player getPlayer(int i) {
return players.get(i);
}
public FreerailsSerializable getTile(int x, int y) {
return map[x][y];
}
public Transaction getTransaction(FreerailsPrincipal p, int i) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = bankAccounts.get(playerIndex, i);
return tats.getT();
}
public GameTime getTransactionTimeStamp(FreerailsPrincipal p, int i) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = bankAccounts.get(playerIndex, i);
return tats.getTimeStamp();
}
public Pair<Transaction, GameTime> getTransactionAndTimeStamp(
FreerailsPrincipal p, int i) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = bankAccounts.get(playerIndex, i);
return new Pair<Transaction, GameTime>(tats.getT(), tats.getTimeStamp());
}
@Override
public int hashCode() {
int result;
result = players.size();
return result;
}
public boolean isPlayer(FreerailsPrincipal p) {
if (p.getWorldIndex() >= 0 && p.getWorldIndex() < players.size()) {
return true;
} else {
return false;
}
}
public FreerailsSerializable removeLast(FreerailsPrincipal p, KEY key) {
int playerIndex = p.getWorldIndex();
return lists.removeLastD3(playerIndex, key.getKeyID());
}
public FreerailsSerializable removeLast(SKEY key) {
return sharedLists.removeLastD2(key.getKeyID());
}
public Activity removeLastActiveEntity(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
int lastID = activityLists.sizeD2(playerIndex) - 1;
Activity act = activityLists.removeLastD3(playerIndex, lastID).act;
activityLists.removeLastD2(playerIndex);
return act;
}
public Activity removeLastActivity(FreerailsPrincipal p, int index) {
int playerIndex = p.getWorldIndex();
if (activityLists.sizeD3(playerIndex, index) < 2)
throw new IllegalStateException();
Activity act = activityLists.removeLastD3(playerIndex, index).act;
return act;
}
/**
* Removes the last player to be added.
*
* @return the player that was removed.
* @throws IllegalStateException
* if any elements belonging to the player have not been
* removed.
*/
public Player removeLastPlayer() {
int playerID = bankAccounts.removeLastD1();
while (lists.sizeD2(playerID) > 0)
lists.removeLastD2(playerID);
lists.removeLastD1();
currentBalance.removeLast();
activityLists.removeLastD1();
return players.removeLast();
}
public Transaction removeLastTransaction(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = bankAccounts.removeLastD2(playerIndex);
Money oldBalance = currentBalance.get(playerIndex);
Money newBalance = new Money(oldBalance.getAmount()
- tats.getT().deltaCash().getAmount());
currentBalance.set(playerIndex, newBalance);
return tats.getT();
}
public void set(FreerailsPrincipal p, KEY key, int index,
FreerailsSerializable element) {
int playerIndex = p.getWorldIndex();
lists.set(playerIndex, key.getKeyID(), index, element);
}
public void set(ITEM item, FreerailsSerializable element) {
items.set(item.getKeyID(), element);
}
public void set(SKEY key, int index, FreerailsSerializable element) {
sharedLists.set(key.getKeyID(), index, element);
}
public void setTile(int x, int y, FreerailsSerializable element) {
map[x][y] = element;
}
public void setTime(GameTime t) {
time = t;
}
void setupItems() {
this.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
time = new GameTime(0);
this.set(ITEM.ECONOMIC_CLIMATE, EconomicClimate.MODERATION);
}
public void setupMap(int mapWidth, int mapHeight) {
map = new FreerailsSerializable[mapWidth][mapHeight];
for (int x = 0; x < mapWidth; x++) {
for (int y = 0; y < mapHeight; y++) {
map[x][y] = FreerailsTile.NULL;
}
}
}
public int size(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
return activityLists.sizeD2(playerIndex);
}
public int size(FreerailsPrincipal p, KEY key) {
int playerIndex = p.getWorldIndex();
return lists.sizeD3(playerIndex, key.getKeyID());
}
public int size(SKEY key) {
return sharedLists.sizeD2(key.getKeyID());
}
public int getNumberOfActiveEntities(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
return activityLists.sizeD2(playerIndex);
}
}

WorldListListener

Full name: jfreerails.world.top.WorldListListener

Documentation

/**
* Classes that need to be notified of changes to the lists on the world object
* should implement this interface.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* Classes that need to be notified of changes to the lists on the world object
* should implement this interface.
*
* @author Luke Lindsay
*
*/
public interface WorldListListener {
void listUpdated(KEY key, int index, FreerailsPrincipal principal);
void itemAdded(KEY key, int index, FreerailsPrincipal principal);
void itemRemoved(KEY key, int index, FreerailsPrincipal principal);
}

KEY

Full name: jfreerails.world.top.KEY

Documentation

/**
* <p>
* This class provides a set of keys to access the lists of elements in the game
* world that are indexed by player.
* </P>
*
* <p>
* It implements the typesafe enum pattern (see Bloch, <I>Effective Java</I>
* item 21)
* </p>
*
* @author Luke
*/

Source Code

/**
* <p>
* This class provides a set of keys to access the lists of elements in the game
* world that are indexed by player.
* </P>
*
* <p>
* It implements the typesafe enum pattern (see Bloch, <I>Effective Java</I>
* item 21)
* </p>
*
* @author Luke
*/
@jfreerails.util.InstanceControlled
public class KEY implements FreerailsSerializable {
private static final long serialVersionUID = 3257572793275987001L;
/** Maps key numbers to KEYs. */
private static final KEY[] keys = new KEY[15];
// START OF KEYS
public static final KEY TRAINS = new KEY();
// public static final KEY TRAIN_POSITIONS = new KEY();
public static final KEY STATIONS = new KEY();
/** The cargo waiting at stations or carried by trains. */
public static final KEY CARGO_BUNDLES = new KEY();
public static final KEY TRAIN_SCHEDULES = new KEY();
// END OF KEYS
private static int numberOfKeys;
private final int keyNumber;
private KEY() {
this.keyNumber = numberOfKeys;
keys[keyNumber] = this;
numberOfKeys++;
}
static int getNumberOfKeys() {
return numberOfKeys;
}
int getKeyID() {
return keyNumber;
}
private Object readResolve() throws ObjectStreamException {
return keys[this.keyNumber];
}
@Override
public String toString() {
return Utils.findConstantFieldName(this);
}
public static KEY getKey(int keyNum) {
return keys[keyNum];
}
}

TypeID

Full name: jfreerails.world.top.TypeID

Documentation

/**
* This class stores an SKEY and an item index.
*
* @author Luke Lindsay
*/

Source Code

/**
* This class stores an SKEY and an item index.
*
* @author Luke Lindsay
*/
public class TypeID {
private final int id;
private final SKEY key;
public TypeID(int id, SKEY key) {
this.id = id;
this.key = key;
}
public SKEY getKey() {
return key;
}
public int getID() {
return id;
}
}

Methods

SKEY

Full name: jfreerails.world.top.SKEY

Documentation

/**
* <p>
* This class provides a set of keys to access the lists of elements in the game
* world that are shared by all players.
* </P>
*
* <p>
* It implements the typesafe enum pattern (see Bloch, <I>Effective Java</I>
* item 21)
* </p>
*
* @author Luke
*/

Source Code

/**
* <p>
* This class provides a set of keys to access the lists of elements in the game
* world that are shared by all players.
* </P>
*
* <p>
* It implements the typesafe enum pattern (see Bloch, <I>Effective Java</I>
* item 21)
* </p>
*
* @author Luke
*/
@jfreerails.util.InstanceControlled
public class SKEY implements FreerailsSerializable {
private static final long serialVersionUID = 3257847679739506737L;
/** Maps key numbers to KEYs. */
private static final SKEY[] keys = new SKEY[getNumberOfKeys()];
// START OF KEYS
public static final SKEY TERRAIN_TYPES = new SKEY();
public static final SKEY WAGON_TYPES = new SKEY();
public static final SKEY CARGO_TYPES = new SKEY();
public static final SKEY CITIES = new SKEY();
public static final SKEY ENGINE_TYPES = new SKEY();
public static final SKEY TRACK_RULES = new SKEY();
// END OF SKEYS
private static int numberOfKeys;
private final int keyNumber;
private SKEY() {
this.keyNumber = numberOfKeys;
keys[keyNumber] = this;
numberOfKeys++;
}
static int getNumberOfKeys() {
return SKEY.class.getFields().length;
}
int getKeyID() {
return keyNumber;
}
private Object readResolve() throws ObjectStreamException {
return keys[this.keyNumber];
}
@Override
public String toString() {
return Utils.findConstantFieldName(this);
}
static SKEY getKey(int keyNum) {
return keys[keyNum];
}
}

WagonAndEngineTypesFactory

Full name: jfreerails.world.top.WagonAndEngineTypesFactory

Documentation

/**
* This class adds hard coded wagon and engine types to the World. Later the
* wagon and engine types will be defined in an xml file, but this will do for
* now.
*
* @author Luke
*
*/

Source Code

/**
* This class adds hard coded wagon and engine types to the World. Later the
* wagon and engine types will be defined in an xml file, but this will do for
* now.
*
* @author Luke
*
*/
public class WagonAndEngineTypesFactory {
public void addTypesToWorld(World w) {
// Wagon types
WagonType[] wagonTypes = new WagonType[] {
new WagonType("Mail", WagonType.MAIL),
new WagonType("Passengers", WagonType.PASSENGER),
new WagonType("Livestock", WagonType.FAST_FREIGHT),
new WagonType("Coffee", WagonType.SLOW_FREIGHT),
new WagonType("Wood", WagonType.BULK_FREIGHT), };
for (int i = 0; i < wagonTypes.length; i++) {
w.add(SKEY.WAGON_TYPES, wagonTypes[i]);
}
// Engine types
EngineType[] engineTypes = new EngineType[] {
new EngineType("Grasshopper", 1000, new Money(10000), 10,
new Money(100)),
new EngineType("Norris", 1000, new Money(10000), 15, new Money(
100)), };
for (int i = 0; i < engineTypes.length; i++) {
w.add(SKEY.ENGINE_TYPES, engineTypes[i]);
}
}
}

Methods

GameRules

Full name: jfreerails.world.top.GameRules

Documentation

/**
* Stores rules governing what players are allowed to do, for example whether
* they can connect their track to the track of other players.
*
* @author Luke
*
*/

Source Code

/**
* Stores rules governing what players are allowed to do, for example whether
* they can connect their track to the track of other players.
*
* @author Luke
*
*/
public class GameRules implements FreerailsSerializable {
private static final long serialVersionUID = 3258125847557978416L;
private final boolean canConnect2OtherRRTrack;
private final boolean mustConnect2ExistingTrack;
public static final GameRules DEFAULT_RULES = new GameRules(true, false);
public static final GameRules NO_RESTRICTIONS = new GameRules(false, true);
@Override
public int hashCode() {
int result;
result = (canConnect2OtherRRTrack ? 1 : 0);
result = 29 * result + (mustConnect2ExistingTrack ? 1 : 0);
return result;
}
private GameRules(boolean mustConnect, boolean canConnect2others) {
canConnect2OtherRRTrack = canConnect2others;
mustConnect2ExistingTrack = mustConnect;
}
public synchronized boolean isCanConnect2OtherRRTrack() {
return canConnect2OtherRRTrack;
}
public synchronized boolean isMustConnect2ExistingTrack() {
return mustConnect2ExistingTrack;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof GameRules)) {
return false;
}
GameRules test = (GameRules) obj;
return this.canConnect2OtherRRTrack == test.canConnect2OtherRRTrack
&& this.mustConnect2ExistingTrack == test.mustConnect2ExistingTrack;
}
}

TransactionAggregator

Full name: jfreerails.world.top.TransactionAggregator

Documentation

/**
*
* Adds up the value of transactions. Implements GoF Template Method pattern.
* Subclasses that aggregate a monetary sum should only override the method
* <code>condition(int)</code>; subclasses that aggregate a non-monetary sum
* should override all 4 protected methods.
*
*
* @author Luke
*
*/

Source Code

/**
*
* Adds up the value of transactions. Implements GoF Template Method pattern.
* Subclasses that aggregate a monetary sum should only override the method
* <code>condition(int)</code>; subclasses that aggregate a non-monetary sum
* should override all 4 protected methods.
*
*
* @author Luke
*
*/
public abstract class TransactionAggregator {
protected final ReadOnlyWorld w;
protected final FreerailsPrincipal principal;
protected Money[] monetaryTotals;
protected int runningTotal = 0;
private final GameTime[] DEFAULT_INTERVAL = new GameTime[] {
GameTime.BIG_BANG, GameTime.END_OF_THE_WORLD };
private GameTime[] timeValues = DEFAULT_INTERVAL;
public GameTime[] getTimes() {
// return defensive copy.
return timeValues.clone();
}
public void setTimes(GameTime[] times) {
if (1 > times.length) {
throw new IllegalArgumentException(
"There must be at least two values.");
}
timeValues = new GameTime[times.length];
timeValues[0] = times[0]; // since we start counting at 1.
for (int i = 1; i < times.length; i++) {
if (times[i].getTicks() < times[i - 1].getTicks()) {
throw new IllegalArgumentException("Time at index " + (i - 1)
+ " > time at index " + i + ".");
}
timeValues[i] = times[i];
}
}
public TransactionAggregator(ReadOnlyWorld w, FreerailsPrincipal principal) {
this.w = w;
this.principal = principal;
}
/** Returns the sum of the appropriate transactions. Do not override. */
final public Money calculateValue() {
Money[] values = calculateValues();
return values[0];
}
/**
* Returns the sum of the appropriate transactions up to (inclusive) each of
* the specified times. Do not override.
*/
final public Money[] calculateValues() {
setTotalsArrayLength(timeValues.length - 1);
int timeIndex = 0;
int numberOfTransactions = w.getNumberOfTransactions(this.principal);
setTotalsArrayLength(timeValues.length - 1);
for (int i = 0; i < numberOfTransactions; i++) {
GameTime time = w.getTransactionTimeStamp(principal, i);
int transactionTime = time.getTicks();
while (timeValues[timeIndex].getTicks() <= transactionTime) {
storeTotalIfAppropriate(timeIndex);
timeIndex++;
if (timeIndex >= timeValues.length) {
/*
* The current transaction occurred after the last of the
* specified times.
*/
return monetaryTotals;
}
}
if (timeIndex > 0 && condition(i)) {
incrementRunningTotal(i);
}
}
/*
* There are no more transactions and the last transaction occurred
* before one or more of the specified times.
*/
while (timeIndex < timeValues.length) {
storeTotalIfAppropriate(timeIndex);
timeIndex++;
}
return monetaryTotals;
}
private void storeTotalIfAppropriate(int timeIndex) {
if (timeIndex > 0) {
storeRunningTotal(timeIndex - 1);
}
}
/**
* Creates a new array with the specified length to store monetary totals
* and sets the running total to zero. Subclasses that aggregate other
* quantities should override this method and create the appropriate arrays.
*/
protected void setTotalsArrayLength(int length) {
monetaryTotals = new Money[length];
runningTotal = 0;
}
protected void incrementRunningTotal(int transactionID) {
Transaction t = w.getTransaction(principal, transactionID);
runningTotal += t.deltaCash().getAmount();
}
/**
* Stores the current running total in the totals array at the specified
* position.
*/
protected void storeRunningTotal(int timeIndex) {
monetaryTotals[timeIndex] = new Money(runningTotal);
}
/** Returns true if we should count the specified transactions. */
abstract protected boolean condition(int transactionID);
}

MutableCargoBundle

Full name: jfreerails.world.cargo.MutableCargoBundle

Documentation

/**
* This CargoBundle implementation uses a <code>java.util.SortedMap</code> to
* map quantities to cargo batches.
*
* @author Luke
*
*/

Source Code

/**
* This CargoBundle implementation uses a <code>java.util.SortedMap</code> to
* map quantities to cargo batches.
*
* @author Luke
*
*/
public class MutableCargoBundle implements CargoBundle {
private final SortedMap<CargoBatch, Integer> sortedMap;
private int updateID = 0;
public MutableCargoBundle() {
sortedMap = new TreeMap<CargoBatch, Integer>();
}
public MutableCargoBundle(ImmutableCargoBundle imcb) {
this();
Iterator<CargoBatch> it = imcb.cargoBatchIterator();
while (it.hasNext()) {
CargoBatch cb = it.next();
addCargo(cb, imcb.getAmount(cb));
}
}
public void addCargo(CargoBatch cb, int amount) {
int amountAlready = this.getAmount(cb);
this.setAmount(cb, amount + amountAlready);
updateID++;
}
/**
* Note, calling hasNext() or next() on the returned iterator throws a
* ConcurrentModificationException if this CargoBundle has changed since the
* iterator was acquired.
*/
public Iterator<CargoBatch> cargoBatchIterator() {
final Iterator<CargoBatch> it = sortedMap.keySet().iterator();
/*
* A ConcurrentModificationException used to get thrown when the amount
* of cargo was set to 0, since this resulted in the key being removed
* from the hashmap. The iterator below throws a
* ConcurrentModificationException whenever this CargoBundle has been
* changed since the iterator was acquired. This should mean that if the
* cargo bundle gets changed while the iterator is in use, you will know
* about it straight away.
*/
return new Iterator<CargoBatch>() {
final int updateIDAtCreation = updateID;
public boolean hasNext() {
if (updateIDAtCreation != updateID) {
throw new ConcurrentModificationException();
}
return it.hasNext();
}
public CargoBatch next() {
if (updateIDAtCreation != updateID) {
throw new ConcurrentModificationException();
}
return it.next();
}
public void remove() {
throw new UnsupportedOperationException(
"Use CargoBundle.setAmount(CargoBatch cb, 0)");
}
};
}
public boolean contains(CargoBatch cb) {
return sortedMap.containsKey(cb);
}
@Override
public boolean equals(Object arg0) {
if (null == arg0) {
return false;
}
if (!(arg0 instanceof CargoBundle)) {
return false;
}
return ImmutableCargoBundle.equals(this, (CargoBundle) arg0);
}
public int getAmount(CargoBatch cb) {
if (contains(cb)) {
Integer i = sortedMap.get(cb);
return i.intValue();
}
return 0;
}
public int getAmount(int cargoType) {
Iterator<CargoBatch> it = cargoBatchIterator();
int amount = 0;
while (it.hasNext()) {
CargoBatch cb = it.next();
if (cb.getCargoType() == cargoType) {
amount += getAmount(cb);
}
}
return amount;
}
@Override
public int hashCode() {
return sortedMap.size();
}
public void setAmount(CargoBatch cb, int amount) {
if (0 == amount) {
sortedMap.remove(cb);
} else {
sortedMap.put(cb, new Integer(amount));
}
updateID++;
}
public int size() {
return sortedMap.size();
}
public ImmutableCargoBundle toImmutableCargoBundle() {
return new ImmutableCargoBundle(sortedMap);
}
@Override
public String toString() {
return toImmutableCargoBundle().toString();
}
}

CargoBundle

Full name: jfreerails.world.cargo.CargoBundle

Documentation

/**
* Represents a collection of CargoBatch objects, providing methods to iterate over batches,
* check for their presence, retrieve amounts by batch or cargo type, and determine the size.
* The iterator is fail-fast and throws ConcurrentModificationException if the bundle is modified
* while iterating.
*
* @see CargoBatch
*/

Source Code

public interface CargoBundle {
/**
* Note, calling hasNext() or next() on the returned iterator throws a
* ConcurrentModificationException if this CargoBundle has changed since the
* iterator was acquired.
*/
Iterator<CargoBatch> cargoBatchIterator();
boolean contains(CargoBatch cb);
int getAmount(CargoBatch cb);
int getAmount(int cargoType);
int size();
}

CargoType

Full name: jfreerails.world.cargo.CargoType

Documentation

/**
* Represents a type of cargo.
*
* @author luke
*/

Source Code

/**
* Represents a type of cargo.
*
* @author luke
*/
final public class CargoType implements FreerailsSerializable {
private static final long serialVersionUID = 3834874680581369912L;
public enum Categories {
Mail(0), Passengers(1), Fast_Freight(2), Slow_Freight(3), Bulk_Freight(
4);
private int nr;
private Categories(int nr) {
this.nr = nr;
}
public int getNumber() {
return nr;
}
public static Categories getCategory(String cat) {
for (Categories cmp : values()) {
if (cmp.toString().equals(cat)) {
return cmp;
}
}
throw new IllegalArgumentException("Category:" + cat + " unknown.");
}
};
public static int getNumberOfCategories() {
return Categories.values().length;
}
private final Categories category;
private final String name;
private final int unitWeight;
public CargoType(int weight, String s, Categories cat) {
unitWeight = weight;
category = cat;
name = s;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof CargoType))
return false;
CargoType other = (CargoType) obj;
return other.unitWeight == this.unitWeight && other.name.equals(name)
&& other.category.equals(category);
}
public Categories getCategory() {
return category;
}
/** Returns the name, replacing any underscores with spaces. */
public String getDisplayName() {
return this.name.replace('_', ' ');
}
public String getName() {
return name;
}
public int getUnitWeight() {
return unitWeight;
}
@Override
public int hashCode() {
int result;
result = unitWeight;
result = 29 * result + category.hashCode();
result = 29 * result + name.hashCode();
return result;
}
@Override
public String toString() {
return name;
}
}

ImmutableCargoBundle

Full name: jfreerails.world.cargo.ImmutableCargoBundle

Documentation

/**
* This class represents a bundle of cargo made up of quantities of cargo from
* different {@link CargoBatch}s.
* <p>
* For example:
* </p>
* <table border="" summary="example">
* <tr>
* <td><strong>Cargo Batch</strong></td>
* <td><strong>Quantity</strong></td>
* </tr>
* <tr>
* <td>passengers from (1, 5) created at 01:00</td>
* <td>2</td>
* </tr>
* <tr>
* <td>passengers from (1, 5) created at 01:25</td>
* <td>1</td>
* </tr>
* <tr>
* <td>coal from (4,10) created at 02:50</td>
* <td>8</td>
* </tr>
* <tr>
* <td>mail from (6, 10) created at 04:45</td>
* <td>10</td>
* </tr>
* </table>
*
* @author Luke
*
*/

Source Code

/**
* This class represents a bundle of cargo made up of quantities of cargo from
* different {@link CargoBatch}s.
* <p>
* For example:
* </p>
* <table border="" summary="example">
* <tr>
* <td><strong>Cargo Batch</strong></td>
* <td><strong>Quantity</strong></td>
* </tr>
* <tr>
* <td>passengers from (1, 5) created at 01:00</td>
* <td>2</td>
* </tr>
* <tr>
* <td>passengers from (1, 5) created at 01:25</td>
* <td>1</td>
* </tr>
* <tr>
* <td>coal from (4,10) created at 02:50</td>
* <td>8</td>
* </tr>
* <tr>
* <td>mail from (6, 10) created at 04:45</td>
* <td>10</td>
* </tr>
* </table>
*
* @author Luke
*
*/
public class ImmutableCargoBundle implements CargoBundle, FreerailsSerializable {
public static final ImmutableCargoBundle EMPTY_BUNDLE = new ImmutableCargoBundle();
private static final long serialVersionUID = 3257566187666814009L;
public static boolean equals(CargoBundle a, CargoBundle b) {
Iterator<CargoBatch> it = a.cargoBatchIterator();
if (a.size() != b.size())
return false;
while (it.hasNext()) {
CargoBatch batch = it.next();
if (a.getAmount(batch) != b.getAmount(batch)) {
return false;
}
}
return true;
}
private final ImInts amounts;
private final ImList<CargoBatch> batches;
private ImmutableCargoBundle() {
batches = new ImList<CargoBatch>();
amounts = new ImInts();
}
public ImmutableCargoBundle(SortedMap<CargoBatch, Integer> sortedMap) {
int size = sortedMap.size();
int[] amountsArray = new int[size];
CargoBatch[] batchesArray = new CargoBatch[size];
int i = 0;
for (CargoBatch batch : sortedMap.keySet()) {
batchesArray[i] = batch;
amountsArray[i] = sortedMap.get(batch);
i++;
}
batches = new ImList<CargoBatch>(batchesArray);
amounts = new ImInts(amountsArray);
}
public Iterator<CargoBatch> cargoBatchIterator() {
return new Iterator<CargoBatch>() {
int index = 0;
public boolean hasNext() {
return index < batches.size();
}
public CargoBatch next() {
CargoBatch o = batches.get(index);
index++;
return o;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public boolean contains(CargoBatch cb) {
for (int i = 0; i < batches.size(); i++) {
if (batches.get(i).equals(cb)) {
return true;
}
}
return false;
}
@Override
public boolean equals(Object arg0) {
if (null == arg0) {
return false;
}
if (!(arg0 instanceof CargoBundle)) {
return false;
}
return equals(this, (CargoBundle) arg0);
}
public int getAmount(CargoBatch cb) {
int amount = 0;
for (int i = 0; i < batches.size(); i++) {
if (batches.get(i).equals(cb)) {
amount += amounts.get(i);
}
}
return amount;
}
public int getAmount(int cargoType) {
int amount = 0;
for (int i = 0; i < batches.size(); i++) {
if (batches.get(i).getCargoType() == cargoType) {
amount += amounts.get(i);
}
}
return amount;
}
@Override
public int hashCode() {
return amounts.size();
}
public int size() {
return batches.size();
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("CargoBundle {\n");
for (int i = 0; i < batches.size(); i++) {
sb.append(amounts.get(i));
sb.append(" units of cargo type ");
sb.append(batches.get(i));
sb.append("\n");
}
sb.append("}");
return sb.toString();
}
}

CargoBatch

Full name: jfreerails.world.cargo.CargoBatch

Documentation

/**
* This class represents a cargo batch (cargo of the same batch is cargo of the
* same type that was produced at the same location at the same time).
*
* @author Luke
*/

Source Code

/**
* This class represents a cargo batch (cargo of the same batch is cargo of the
* same type that was produced at the same location at the same time).
*
* @author Luke
*/
public class CargoBatch implements FreerailsSerializable,
Comparable<CargoBatch> {
private static final long serialVersionUID = 3257006557605540149L;
private final int cargoType;
private final int sourceX;
private final int sourceY;
private final int stationOfOrigin;
private final long timeCreated;
public CargoBatch(int type, int x, int y, long time, int origin) {
cargoType = type;
sourceX = x;
sourceY = y;
timeCreated = time;
stationOfOrigin = origin;
}
public int getStationOfOrigin() {
return stationOfOrigin;
}
public int getCargoType() {
return cargoType;
}
public int getSourceX() {
return sourceX;
}
public int getSourceY() {
return sourceY;
}
public long getTimeCreated() {
return timeCreated;
}
@Override
public boolean equals(Object o) {
if (o instanceof CargoBatch) {
CargoBatch test = (CargoBatch) o;
if (test.getCargoType() == this.cargoType
&& test.getSourceX() == this.sourceX
&& test.sourceY == this.sourceY
&& test.timeCreated == this.timeCreated
&& test.stationOfOrigin == this.stationOfOrigin) {
return true;
}
return false;
}
return false;
}
@Override
public int hashCode() {
int result = 17;
result = 37 * result + this.cargoType;
result = 37 * result + this.sourceX;
result = 37 * result + this.sourceY;
result = 37 * result + this.stationOfOrigin;
result = 37 * result
+ (int) (this.timeCreated ^ (this.timeCreated >>> 32));
return result;
}
public int compareTo(CargoBatch o) {
if (timeCreated != o.timeCreated)
return (int) (timeCreated - o.timeCreated);
if (cargoType != o.cargoType)
return (cargoType - o.cargoType);
if (stationOfOrigin != o.stationOfOrigin)
return (stationOfOrigin - o.stationOfOrigin);
if (sourceX != o.sourceX)
return (sourceX - o.sourceX);
if (sourceY != o.sourceY)
return (sourceY - o.sourceY);
return 0;
}
}

TrackConfiguration

Full name: jfreerails.world.track.TrackConfiguration

Documentation

/**
* An instance of this class represents one of the possible track configurations
* in a map square - the combinations of directions in which track can be laid.
* Instances of this class cannot be created and must be obtained via the static
* methods herein.
*
* @author Luke
*/

Source Code

/**
* An instance of this class represents one of the possible track configurations
* in a map square - the combinations of directions in which track can be laid.
* Instances of this class cannot be created and must be obtained via the static
* methods herein.
*
* @author Luke
*/
final public class TrackConfiguration implements FlatTrackTemplate {
private static final long serialVersionUID = 3618695301330974512L;
private static final ArrayList<TrackConfiguration> flatTrackConfigurations = setupConfigurations();
public static final int LENGTH_OF_STRAIGHT_TRACK_PIECE = 200;
/**
* @return the superposition of two track templates
*/
public static TrackConfiguration add(FlatTrackTemplate c,
FlatTrackTemplate v) {
/*
* int x=v.getX()+1; int y=v.getY()+1; int oldTemplate
* =c.getTrackGraphicsNumber(); int newTemplate = oldTemplate | (1 <<
* (3 * y + x));
*/
int newTemplate = c.get9bitTemplate() | v.get9bitTemplate();
return from9bitTemplate(newTemplate);
}
public static TrackConfiguration from9bitTemplate(int i) {
return flatTrackConfigurations.get(i);
}
public static TrackConfiguration getFlatInstance(Step v) {
return from9bitTemplate(v.get9bitTemplate());
}
public static TrackConfiguration getFlatInstance(String trackTemplate) {
int i = TrackConfiguration.stringTemplate2Int(trackTemplate);
return (flatTrackConfigurations.get(i));
}
private static ArrayList<TrackConfiguration> setupConfigurations() {
ArrayList<TrackConfiguration> configurations = new ArrayList<TrackConfiguration>(
512);
for (int i = 0; i < 512; i++) {
configurations.add(i, new TrackConfiguration(i));
}
return configurations;
}
public static int stringTemplate2Int(String templateString) {
// Hack - so that result is as expected by earlier written code.
StringBuffer strb = new StringBuffer(templateString);
strb = strb.reverse();
templateString = strb.toString();
// End of hack
return Integer.parseInt(templateString, 2);
}
/**
* @return the TrackConfiguration representing the track section c minus the
* track sections represented by v.
*/
public static TrackConfiguration subtract(FlatTrackTemplate c,
FlatTrackTemplate v) {
/*
* int x=v.getX()+1; int y=v.getY()+1; int oldTemplate
* =c.getTrackGraphicsNumber(); int newTemplate = oldTemplate ^ (1 <<
* (3 * y + x));
*/
int newTemplate = c.get9bitTemplate() & (~v.get9bitTemplate());
return from9bitTemplate(newTemplate);
}
private final int length;
private final int configuration;
private TrackConfiguration(int configuration) {
this.configuration = configuration;
// Calculate length.
int tempLength = 0;
Step[] vectors = Step.getList();
for (int i = 0; i < vectors.length; i++) {
if (this.contains(vectors[i].get9bitTemplate())) {
tempLength += vectors[i].getLength();
}
}
length = tempLength;
}
public boolean contains(FlatTrackTemplate ftt) {
int trackTemplate = ftt.get9bitTemplate();
return contains(trackTemplate);
}
public boolean contains(int trackTemplate) {
if ((trackTemplate | this.configuration) == this.configuration) {
return true;
}
return false;
}
public int get8bitTemplate() {
int newTemplate = 0;
Step[] vectors = Step.getList();
for (int i = 0; i < vectors.length; i++) {
if (this.contains(vectors[i])) {
newTemplate = newTemplate | vectors[i].get8bitTemplate();
}
}
return newTemplate;
}
/**
* @return an int representing this track configuration.
*/
public int get9bitTemplate() {
return configuration;
}
/**
* Returns the length of track used in this configuration. Used to calculate
* the cost of building track.
*/
public int getLength() {
return length;
}
public Iterator getPossibleConfigurationsIterator() {
return flatTrackConfigurations.iterator();
}
public int getTrackGraphicsID() {
return configuration;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final TrackConfiguration that = (TrackConfiguration) o;
if (configuration != that.configuration)
return false;
return true;
}
@Override
public int hashCode() {
return configuration;
}
private Object readResolve() throws ObjectStreamException {
return TrackConfiguration.from9bitTemplate(this.configuration);
}
/**
* Returns a String representing this configuration, for example "north,
* south".
*/
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
int matches = 0;
if (contains(TrackConfiguration.getFlatInstance("000010000"))) {
sb.append("tile center");
} else {
sb.append("no tile center");
}
for (int i = 0; i < 8; i++) {
Step v = Step.getInstance(i);
if (contains(v)) {
sb.append(",");
sb.append(v);
matches++;
}
}
return sb.toString().trim();
}
}

TrackRule

Full name: jfreerails.world.track.TrackRule

Documentation

/**
* Defines methods to access the properties of a track type.
*
* @author Luke Lindsay 09 October 2001
*/

Source Code

/**
* Defines methods to access the properties of a track type.
*
* @author Luke Lindsay 09 October 2001
*/
public interface TrackRule extends FreerailsSerializable, Comparable<TrackRule> {
public enum TrackCategories {
track, bridge, tunnel, station, non
}
TrackCategories getCategory();
boolean canBuildOnThisTerrainType(TerrainType.Category TerrainType);
boolean isStation();
boolean isDouble();
Money getPrice();
Money getFixedCost();
Money getMaintenanceCost();
int getStationRadius();
String getTypeName();
boolean testTrackPieceLegality(int a9bitTemplate);
boolean trackPieceIsLegal(TrackConfiguration config);
int getMaximumConsecutivePieces();
Step[] getLegalRoutes(Step directionComingFrom);
Iterator<TrackConfiguration> getLegalConfigurationsIterator();
}

FreerailsTile

Full name: jfreerails.world.track.FreerailsTile

Documentation

/**
* A tile on the map.
*
* Instances are stored in a HashMap to avoid creating 100,000s of objects.
*
* @author Luke
*/

Source Code

/**
* A tile on the map.
*
* Instances are stored in a HashMap to avoid creating 100,000s of objects.
*
* @author Luke
*/
public class FreerailsTile implements TerrainTile,
FreerailsSerializable {
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final FreerailsTile that = (FreerailsTile) o;
if (terrainType != that.terrainType)
return false;
if (trackPiece != null ? !trackPiece.equals(that.trackPiece)
: that.trackPiece != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = (trackPiece != null ? trackPiece.hashCode() : 0);
result = 29 * result + terrainType;
return result;
}
private static final long serialVersionUID = 3617574907538847544L;
public static final FreerailsTile NULL = new FreerailsTile(0);
private final TrackPiece trackPiece;
private final int terrainType;
private static HashMap<FreerailsTile, FreerailsTile> instances = new HashMap<FreerailsTile, FreerailsTile>();
public static FreerailsTile getInstance(int terrainType) {
FreerailsTile tile = new FreerailsTile(terrainType);
if (instances.containsKey(tile)) {
return instances.get(tile);
}
instances.put(tile, tile);
return tile;
}
public static FreerailsTile getInstance(int terrainType,
TrackPiece trackPiece) {
FreerailsTile tile = new FreerailsTile(terrainType, trackPiece);
if (instances.containsKey(tile)) {
return instances.get(tile);
}
instances.put(tile, tile);
return tile;
}
private Object readResolve() throws ObjectStreamException {
if (instances.containsKey(this)) {
return instances.get(this);
}
instances.put(this, this);
return this;
}
private FreerailsTile(int terrainType) {
this.terrainType = terrainType;
this.trackPiece = NullTrackPiece.getInstance();
}
private FreerailsTile(int terrainType, TrackPiece trackPiece) {
this.terrainType = terrainType;
this.trackPiece = trackPiece;
}
public int getTerrainTypeID() {
return terrainType;
}
@Override
public String toString() {
return "trackPiece=" + trackPiece.toString() + " and terrainType is "
+ terrainType;
}
public TrackPiece getTrackPiece() {
return trackPiece;
}
public boolean hasTrack(){
return trackPiece.getTrackTypeID() != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER;
}
}

LegalTrackPlacement

Full name: jfreerails.world.track.LegalTrackPlacement

Documentation

/**
* This class encapsulates the rules governing where, that is, on what terrain,
* track of a given type can be built.
*
* @author lindsal
*/

Source Code

/**
* This class encapsulates the rules governing where, that is, on what terrain,
* track of a given type can be built.
*
* @author lindsal
*/
public final class LegalTrackPlacement implements FreerailsSerializable {
private static final long serialVersionUID = 3616445687756437049L;
private final ImHashSet<TerrainType.Category> terrainTypes;// = new
// HashSet<TerrainType.Category>();
public enum PlacementRule {
ONLY_ON_THESE, ANYWHERE_EXCEPT_ON_THESE
}
private final PlacementRule placementRule;
@Override
public int hashCode() {
return (placementRule != null ? placementRule.hashCode() : 0);
}
public LegalTrackPlacement(HashSet<TerrainType.Category> types,
PlacementRule placementRule) {
this.placementRule = placementRule;
Iterator<TerrainType.Category> iterator = types.iterator();
HashSet<TerrainType.Category> temp = new HashSet<TerrainType.Category>();
while (iterator.hasNext()) {
temp.add(iterator.next());
}
terrainTypes = new ImHashSet<TerrainType.Category>(temp);
}
public boolean canBuildOnThisTerrain(TerrainType.Category terrainType) {
if (PlacementRule.ONLY_ON_THESE == placementRule) {
return terrainTypes.contains(terrainType);
}
return !terrainTypes.contains(terrainType);
}
@Override
public boolean equals(Object o) {
if (o instanceof LegalTrackPlacement) {
LegalTrackPlacement test = (LegalTrackPlacement) o;
if (this.placementRule.equals(test.getPlacementRule())
&& this.terrainTypes.equals(test.terrainTypes)) {
return true;
}
return false;
}
return false;
}
public PlacementRule getPlacementRule() {
return placementRule;
}
}

EightRotationsOfTrackPieceProducer

Full name: jfreerails.world.track.EightRotationsOfTrackPieceProducer

Documentation

/**
* This class provides a method to get the eight rotations of a track template.
* E.g. if the template is: 010 010 110 it returns: 010 001 100 010 110 111 110
* 100 000 etc.
*
*
* @author Luke Lindsay
* @version 1.0
*/

Source Code

/**
* This class provides a method to get the eight rotations of a track template.
* E.g. if the template is: 010 010 110 it returns: 010 001 100 010 110 111 110
* 100 000 etc.
*
*
* @author Luke Lindsay
* @version 1.0
*/
public class EightRotationsOfTrackPieceProducer {
/**
* The method that returns the rotations.
*
* @param trackBlueprint
* A 9bit value that serves as the template.
* @return An array of 8 9-bit values that have been generated by rotating
* the template.
*/
public static int[] getRotations(int trackBlueprint) {
int trackTemplate = trackBlueprint;
int[] derivedTrackPieces = new int[8];
for (int i = 0; i < 8; i++) {
derivedTrackPieces[i] = trackTemplate;
boolean[][] trackTemplateBooleanArray = getTrackBooleanArray(trackTemplate);
trackTemplateBooleanArray = rotateTrackNodeClockwise(trackTemplateBooleanArray);
trackTemplate = getTrackGraphicID(trackTemplateBooleanArray);
}
return derivedTrackPieces;
}
private static boolean[][] getTrackBooleanArray(int trackGraphicInt) {
boolean[][] trackBooleanArray = new boolean[3][3];
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
if (((trackGraphicInt >> (3 * y + x)) & 1) == 1) {
trackBooleanArray[x][y] = true;
}
}
}
return trackBooleanArray;
}
private static int getTrackGraphicID(boolean[][] railsList) {
int trackGraphicNumber = 0;
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
if (railsList[x][y]) {
trackGraphicNumber = trackGraphicNumber
| (1 << (3 * y + x));
}
}
}
return trackGraphicNumber;
}
private static boolean[][] rotateTrackNodeClockwise(boolean[][] source) {
Point[][] grabValueFrom = new Point[3][];
grabValueFrom[0] = new Point[] { new Point(0, 1), new Point(0, 0),
new Point(1, 0) };
grabValueFrom[1] = new Point[] { new Point(0, 2), new Point(1, 1),
new Point(2, 0) };
grabValueFrom[2] = new Point[] { new Point(1, 2), new Point(2, 2),
new Point(2, 1) };
/*
* I think there is a neater way of doing this, let me know if you know
* it! Luke
*/
boolean[][] output = new boolean[3][3];
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
Point point = grabValueFrom[y][x];
/*
* y,x because of the way I defined grabValueFrom[][] above.
*/
output[x][y] = source[point.x][point.y];
}
}
return output;
}
}

TrackRuleProperties

Full name: jfreerails.world.track.TrackRuleProperties

Documentation

/**
* Stores some of the properties of a track type.
*
* @author Luke
*/

Source Code

/**
* Stores some of the properties of a track type.
*
* @author Luke
*/
final public class TrackRuleProperties implements FreerailsSerializable {
private static final long serialVersionUID = 3618704101752387641L;
private final boolean enableDoubleTrack;
private final Money maintenanceCost;
private final Money price;
private final Money fixedCost;
private final TrackRule.TrackCategories category;
private final int rGBvalue;
private final int stationRadius;
private final String typeName;
public TrackRuleProperties(int rgb, boolean doubleTrack, String name,
TrackRule.TrackCategories c, int radius, int price,
int maintenance, int fixedCost) {
stationRadius = radius;
rGBvalue = rgb;
enableDoubleTrack = doubleTrack;
typeName = name;
category = c;
this.price = new Money(price);
this.maintenanceCost = new Money(maintenance);
this.fixedCost = new Money(fixedCost);
}
@Override
public boolean equals(Object o) {
if (o instanceof TrackRuleProperties) {
TrackRuleProperties test = (TrackRuleProperties) o;
if (rGBvalue == test.getRGBvalue()
&& enableDoubleTrack == test.isEnableDoubleTrack()
&& typeName.equals(test.getTypeName())
&& category == test.category
&& stationRadius == test.stationRadius) {
return true;
}
return false;
}
return false;
}
public Money getMaintenanceCost() {
return maintenanceCost;
}
public Money getPrice() {
return price;
}
private int getRGBvalue() {
return rGBvalue;
}
public int getStationRadius() {
return stationRadius;
}
public String getTypeName() {
return typeName;
}
@Override
public int hashCode() {
int result;
result = rGBvalue;
result = 29 * result + (enableDoubleTrack ? 1 : 0);
result = 29 * result + typeName.hashCode();
result = 29 * result + category.hashCode();
result = 29 * result + stationRadius;
result = 29 * result + price.hashCode();
result = 29 * result + fixedCost.hashCode();
result = 29 * result + maintenanceCost.hashCode();
return result;
}
public boolean isEnableDoubleTrack() {
return enableDoubleTrack;
}
public boolean isStation() {
return category.equals(TrackRule.TrackCategories.station);
}
public TrackRule.TrackCategories getCategory() {
return category;
}
public Money getFixedCost() {
return fixedCost;
}
}

TrackPiece

Full name: jfreerails.world.track.TrackPiece

Documentation

/**
* Defines methods to access the properties of the track on a tile.
*
* @author Luke
*/

Source Code

/**
* Defines methods to access the properties of the track on a tile.
*
* @author Luke
*/
public interface TrackPiece extends FreerailsSerializable {
int getTrackGraphicID();
int getTrackTypeID();
TrackRule getTrackRule();
TrackConfiguration getTrackConfiguration();
int getOwnerID();
}

TrackRuleImpl

Full name: jfreerails.world.track.TrackRuleImpl

Documentation

/**
* This class encapsulates the rules that apply to a type of track node. They
* concern: the legal routes trains can travel across the node, whether the
* node's track can be doubled, on which terrain types it can be built, and the
* maximum number of consecutive nodes of this type (used for bridges and
* tunnels).
*
* @author Luke Lindsay 09 October 2001
*/

Source Code

/**
* This class encapsulates the rules that apply to a type of track node. They
* concern: the legal routes trains can travel across the node, whether the
* node's track can be doubled, on which terrain types it can be built, and the
* maximum number of consecutive nodes of this type (used for bridges and
* tunnels).
*
* @author Luke Lindsay 09 October 2001
*/
final public class TrackRuleImpl implements TrackRule {
private static final long serialVersionUID = 3257281414171801401L;
private final LegalTrackConfigurations legalConfigurations;
private final LegalTrackPlacement legalTrackPlacement;
private final TrackRuleProperties properties;
/*
* Track templates are 9 bit values, so there are 512 possible templates. If
* legalTrackTemplate[x]==true, then x is a legal track-template. Example:
* 000 111 000 This represents a horizontal straight.
*/
public TrackRuleImpl(TrackRuleProperties p, LegalTrackConfigurations lc,
LegalTrackPlacement ltp) {
if (null == p || null == lc || null == ltp) {
throw new java.lang.IllegalArgumentException();
}
properties = p;
legalConfigurations = lc;
legalTrackPlacement = ltp;
}
public boolean canBuildOnThisTerrainType(TerrainType.Category TerrainType) {
return legalTrackPlacement.canBuildOnThisTerrain(TerrainType);
}
/**
* If the specified object is a track rule, comparison is by category then
* price.
*/
public int compareTo(TrackRule otherRule) {
int comp = otherRule.getCategory().compareTo(getCategory());
if (comp != 0) {
return -comp;
}
long dPrice = this.properties.getPrice().getAmount()
- otherRule.getPrice().getAmount();
return (int) dPrice;
}
@Override
public boolean equals(Object o) {
if (o instanceof TrackRuleImpl) {
TrackRuleImpl trackRuleImpl = (TrackRuleImpl) o;
boolean propertiesFieldsEqual = this.properties
.equals(trackRuleImpl.getProperties());
boolean legalConfigurationsEqual = this.legalConfigurations
.equals(trackRuleImpl.getLegalConfigurations());
boolean legalTrackPlacementEqual = this.legalTrackPlacement
.equals(trackRuleImpl.getLegalTrackPlacement());
if (propertiesFieldsEqual && legalConfigurationsEqual
&& legalTrackPlacementEqual) {
return true;
}
return false;
}
return false;
}
public TrackRule.TrackCategories getCategory() {
return properties.getCategory();
}
public LegalTrackConfigurations getLegalConfigurations() {
return legalConfigurations;
}
public Iterator<TrackConfiguration> getLegalConfigurationsIterator() {
return legalConfigurations.getLegalConfigurationsIterator();
}
public Step[] getLegalRoutes(Step directionComingFrom) {
// TODO add code..
return null;
}
public LegalTrackPlacement getLegalTrackPlacement() {
return legalTrackPlacement;
}
public Money getMaintenanceCost() {
return properties.getMaintenanceCost();
}
public int getMaximumConsecutivePieces() {
return legalConfigurations.getMaximumConsecutivePieces();
}
public Money getPrice() {
return this.properties.getPrice();
}
public TrackRuleProperties getProperties() {
return properties;
}
public int getStationRadius() {
return this.properties.getStationRadius();
}
public String getTypeName() {
return properties.getTypeName();
}
@Override
public int hashCode() {
int result;
result = properties.hashCode();
result = 29 * result + legalConfigurations.hashCode();
result = 29 * result + legalTrackPlacement.hashCode();
return result;
}
public boolean isStation() {
return properties.isStation();
}
public boolean testTrackPieceLegality(int trackTemplateToTest) {
TrackConfiguration trackConfiguration = TrackConfiguration
.from9bitTemplate(trackTemplateToTest);
return legalConfigurations
.trackConfigurationIsLegal(trackConfiguration);
}
@Override
public String toString() {
return getTypeName();
}
public boolean trackPieceIsLegal(TrackConfiguration config) {
return legalConfigurations.trackConfigurationIsLegal(config);
}
public boolean isDouble() {
return properties.isEnableDoubleTrack();
}
public Money getFixedCost() {
return properties.getFixedCost();
}
}

TrackPieceImpl

Full name: jfreerails.world.track.TrackPieceImpl

Documentation

/**
* Represents the track on a tile.
*
* @author Luke
*/

Source Code

/**
* Represents the track on a tile.
*
* @author Luke
*/
final public class TrackPieceImpl implements TrackPiece {
private static final long serialVersionUID = 4049080423458027569L;
private final TrackConfiguration configuration;
private final TrackRule trackType;
private final int ownerID;
private final int ruleNumber;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final TrackPieceImpl that = (TrackPieceImpl) o;
if (ownerID != that.ownerID)
return false;
if (ruleNumber != that.ruleNumber)
return false;
if (!configuration.equals(that.configuration))
return false;
if (!trackType.equals(that.trackType))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = configuration.hashCode();
result = 29 * result + trackType.hashCode();
result = 29 * result + ownerID;
result = 29 * result + ruleNumber;
return result;
}
public TrackPieceImpl(TrackConfiguration c, TrackRule type, int owner,
int rule) {
configuration = c;
trackType = type;
ownerID = owner;
ruleNumber = rule;
}
public int getTrackGraphicID() {
return configuration.getTrackGraphicsID();
}
public TrackRule getTrackRule() {
return trackType;
}
public TrackConfiguration getTrackConfiguration() {
return configuration;
}
public int getOwnerID() {
return ownerID;
}
public int getTrackTypeID() {
return ruleNumber;
}
}

LegalTrackConfigurations

Full name: jfreerails.world.track.LegalTrackConfigurations

Documentation

/**
* Stores the legal track configurations for a type of track.
*
* @author Luke.
*/

Source Code

/**
* Stores the legal track configurations for a type of track.
*
* @author Luke.
*/
final public class LegalTrackConfigurations implements FreerailsSerializable {
private static final long serialVersionUID = 3617295631735928119L;
private final ImHashSet<TrackConfiguration> legalConfigs;// = new
// HashSet<TrackConfiguration>();
private final int maximumConsecutivePieces;
public LegalTrackConfigurations(int max,
ArrayList<String> legalTrackTemplatesArrayList) {
maximumConsecutivePieces = max;
HashSet<TrackConfiguration> temp = new HashSet<TrackConfiguration>();
// Iterate over the track templates.
for (int i = 0; i < legalTrackTemplatesArrayList.size(); i++) {
String trackTemplateString = legalTrackTemplatesArrayList.get(i);
processTemplate(trackTemplateString, temp);
}
legalConfigs = new ImHashSet<TrackConfiguration>(temp);
}
public LegalTrackConfigurations(int max, String[] legalTrackTemplatesArray) {
maximumConsecutivePieces = max;
HashSet<TrackConfiguration> temp = new HashSet<TrackConfiguration>();
for (int i = 0; i < legalTrackTemplatesArray.length; i++) {
processTemplate(legalTrackTemplatesArray[i], temp);
}
legalConfigs = new ImHashSet<TrackConfiguration>(temp);
}
@Override
public boolean equals(Object o) {
if (o instanceof LegalTrackConfigurations) {
LegalTrackConfigurations test = (LegalTrackConfigurations) o;
if (this.maximumConsecutivePieces == test
.getMaximumConsecutivePieces()
&& this.legalConfigs.equals(test.legalConfigs)) {
return true;
}
return false;
}
return false;
}
public Iterator<TrackConfiguration> getLegalConfigurationsIterator() {
return legalConfigs.iterator();
}
public int getMaximumConsecutivePieces() {
return maximumConsecutivePieces;
}
@Override
public int hashCode() {
int result;
result = maximumConsecutivePieces;
result = 29 * result
+ (legalConfigs != null ? legalConfigs.hashCode() : 0);
return result;
}
static private void processTemplate(String trackTemplateString,
HashSet<TrackConfiguration> temp) {
int trackTemplate = Integer.parseInt(trackTemplateString, 2);
// Check for invalid parameters.
if ((trackTemplate > 511) || (trackTemplate < 0)) {
throw new IllegalArgumentException("trackTemplate = "
+ trackTemplate + ", it should be in the range 0-511");
}
int[] rotationsOfTrackTemplate = EightRotationsOfTrackPieceProducer
.getRotations(trackTemplate);
for (int k = 0; k < rotationsOfTrackTemplate.length; k++) {
int i = rotationsOfTrackTemplate[k];
TrackConfiguration trackConfiguration = TrackConfiguration
.from9bitTemplate(i);
if (!temp.contains(trackConfiguration)) {
temp.add(trackConfiguration);
}
}
}
public boolean trackConfigurationIsLegal(
TrackConfiguration trackConfiguration) {
return legalConfigs.contains(trackConfiguration);
}
}

NullTrackType

Full name: jfreerails.world.track.NullTrackType

Documentation

/**
* The type of a Null track piece. TODO maybe it would be simpler to get rid of
* this and just check against null!
*
* @author lindsal
*/

Source Code

/**
* The type of a Null track piece. TODO maybe it would be simpler to get rid of
* this and just check against null!
*
* @author lindsal
*/
final public class NullTrackType implements TrackRule {
private static final long serialVersionUID = 3257849891614306614L;
public static final int NULL_TRACK_TYPE_RULE_NUMBER = -999;
private static final NullTrackType nullTrackType = new NullTrackType();
private NullTrackType() {
}
private Object readResolve() throws ObjectStreamException {
return nullTrackType;
}
public static NullTrackType getInstance() {
return nullTrackType;
}
public boolean canBuildOnThisTerrainType(TerrainType.Category TerrainType) {
return true; // No track is possible anywhere.
}
public Step[] getLegalRoutes(
jfreerails.world.common.Step directionComingFrom) {
return new Step[0];
}
public int getMaximumConsecutivePieces() {
return -1;
}
public String getTypeName() {
return "NullTrackType";
}
public boolean testTrackPieceLegality(int trackTemplateToTest) {
if (trackTemplateToTest != 0) {
return false;
}
return true;
}
public boolean trackPieceIsLegal(TrackConfiguration config) {
return testTrackPieceLegality(config.getTrackGraphicsID());
}
public Iterator<TrackConfiguration> getLegalConfigurationsIterator() {
throw new UnsupportedOperationException("Method not implemented yet!");
}
public TrackPiece getTrackPiece(TrackConfiguration config, int owner) {
throw new UnsupportedOperationException("Method not implemented yet!");
}
public boolean isStation() {
return false;
}
@Override
public boolean equals(Object o) {
return o == this;
}
@Override
public int hashCode() {
return 666;
}
public int getStationRadius() {
return 0;
}
public Money getPrice() {
return new Money(0);
}
public Money getMaintenanceCost() {
return new Money(0);
}
public TrackCategories getCategory() {
return TrackCategories.non;
}
public int compareTo(TrackRule arg0) {
// TODO Auto-generated method stub
return 0;
}
public boolean isDouble() {
return false;
}
public Money getFixedCost() {
return Money.ZERO;
}
}

TrackSection

Full name: jfreerails.world.track.TrackSection

Documentation

/**
* Represents the track connecting two adjacent tiles.
*
* @author Luke
*
*/

Source Code

/**
* Represents the track connecting two adjacent tiles.
*
* @author Luke
*
*/
public class TrackSection implements FreerailsSerializable {
private static final long serialVersionUID = -3776624056097990938L;
private final Step step;
private final ImPoint tile;
public TrackSection(final Step step, final ImPoint tile) {
ImPoint otherTile = Step.move(tile, step);
if(tile.compareTo(otherTile) > 0){
this.step = step.getOpposite();
this.tile = otherTile;
}else{
this.step = step;
this.tile = tile;
}
}
@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((step == null) ? 0 : step.hashCode());
result = PRIME * result + ((tile == null) ? 0 : tile.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final TrackSection other = (TrackSection) obj;
if (step == null) {
if (other.step != null)
return false;
} else if (!step.equals(other.step))
return false;
if (tile == null) {
if (other.tile != null)
return false;
} else if (!tile.equals(other.tile))
return false;
return true;
}
@Override
public String toString() {
return tile.toString()+ " "+ step.toString();
}
public ImPoint tileA(){
return tile;
}
public ImPoint tileB(){
return Step.move(tile, step);
}
}

NullTrackPiece

Full name: jfreerails.world.track.NullTrackPiece

Documentation

/**
* A track piece that doesn't exist - using this avoids needing to check against
* null before calling the methods on a track piece.
*
* @author lindsal
*/

Source Code

/**
* A track piece that doesn't exist - using this avoids needing to check against
* null before calling the methods on a track piece.
*
* @author lindsal
*/
final public class NullTrackPiece implements TrackPiece {
private static final long serialVersionUID = 3258413915376268599L;
private static final TrackPiece nullTrackPiece = new NullTrackPiece();
private static final int NO_OWNER = Integer.MIN_VALUE;
private NullTrackPiece() {
}
public static TrackPiece getInstance() {
return nullTrackPiece;
}
public int getTrackGraphicID() {
return 0;
}
public TrackRule getTrackRule() {
return NullTrackType.getInstance();
}
public TrackConfiguration getTrackConfiguration() {
return TrackConfiguration.from9bitTemplate(0);
}
private Object readResolve() throws ObjectStreamException {
return nullTrackPiece;
}
@Override
public boolean equals(Object o) {
return o == this;
}
@Override
public int hashCode() {
return 777;
}
public int getOwnerID() {
return NO_OWNER;
}
public int getTrackTypeID() {
return NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER;
}
}

TrainModel

Full name: jfreerails.world.train.TrainModel

Documentation

/**
* Represents a train.
*
* @author Luke
*/

Source Code

/**
* Represents a train.
*
* @author Luke
*/
public class TrainModel implements FreerailsSerializable {
public static final int WAGON_LENGTH = 24;
private static final long serialVersionUID = 3545235825756812339L;
public static final int MAX_NUMBER_OF_WAGONS = 6;
public static final int MAX_TRAIN_LENGTH = (1 + MAX_NUMBER_OF_WAGONS)
* WAGON_LENGTH;
private final int scheduleId;
private final int engineTypeId;
private final ImInts wagonTypes;
private final int cargoBundleId;
@Override
public int hashCode() {
int result;
result = scheduleId;
result = 29 * result + engineTypeId;
result = 29 * result + cargoBundleId;
return result;
}
public TrainModel getNewInstance(int newEngine, ImInts newWagons) {
return new TrainModel(newEngine, newWagons, this.getScheduleID(), this
.getCargoBundleID());
}
public TrainModel(int engine, ImInts wagons, int scheduleID, int BundleId) {
engineTypeId = engine;
wagonTypes = wagons;
scheduleId = scheduleID;
cargoBundleId = BundleId;
}
public TrainModel(ImInts wagons, int BundleId) {
wagonTypes = wagons;
cargoBundleId = BundleId;
engineTypeId = 0;
scheduleId = 0;
}
public TrainModel(int engine, ImInts wagons, int scheduleID) {
engineTypeId = engine;
wagonTypes = wagons;
scheduleId = scheduleID;
cargoBundleId = 0;
}
public TrainModel(int engine) {
engineTypeId = engine;
wagonTypes = new ImInts(0, 1, 2);
scheduleId = 0;
cargoBundleId = 0;
}
public int getLength() {
return (1 + wagonTypes.size()) * WAGON_LENGTH; // Engine + wagons.
}
public boolean canAddWagon() {
return wagonTypes.size() < MAX_NUMBER_OF_WAGONS;
}
public int getNumberOfWagons() {
return wagonTypes.size();
}
public int getWagon(int i) {
return wagonTypes.get(i);
}
public int getEngineType() {
return engineTypeId;
}
public int getCargoBundleID() {
return cargoBundleId;
}
public int getScheduleID() {
return scheduleId;
}
public ImInts getConsist() {
return wagonTypes;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof TrainModel) {
TrainModel test = (TrainModel) obj;
boolean b = this.cargoBundleId == test.cargoBundleId
&& this.engineTypeId == test.engineTypeId
&& this.wagonTypes.equals(test.wagonTypes)
&& this.scheduleId == test.scheduleId;
return b;
}
return false;
}
}

TrainPathIterator

Full name: jfreerails.world.train.TrainPathIterator

Documentation

/**
* Exposes the path of a train. TODO needs better comment
*
* @author Luke Lindsay
*
*/

Source Code

/**
* Exposes the path of a train. TODO needs better comment
*
* @author Luke Lindsay
*
*/
public class TrainPathIterator implements FreerailsPathIterator {
private static final long serialVersionUID = 3256999977816502584L;
private final FreerailsIntIterator intIterator;
private final PositionOnTrack p1 = new PositionOnTrack();
private final PositionOnTrack p2 = new PositionOnTrack();
private static final int tileSize = Constants.TILE_SIZE;
public TrainPathIterator(FreerailsIntIterator i) {
intIterator = i;
p2.setValuesFromInt(intIterator.nextInt());
}
public boolean hasNext() {
return intIterator.hasNextInt();
}
public void nextSegment(IntLine line) {
p1.setValuesFromInt(p2.toInt());
line.x1 = p1.getX() * tileSize + tileSize / 2;
line.y1 = p1.getY() * tileSize + tileSize / 2;
p2.setValuesFromInt(intIterator.nextInt());
line.x2 = p2.getX() * tileSize + tileSize / 2;
line.y2 = p2.getY() * tileSize + tileSize / 2;
}
}

SpeedAgainstTime

Full name: jfreerails.world.train.SpeedAgainstTime

Documentation

/**
* Represents a model of distance traveled over time, providing methods to calculate
* distance from time, time from distance, and derived quantities such as velocity and
* acceleration. This interface defines the contract for objects that represent the
* relationship between time and distance, ensuring valid input ranges and throwing
* exceptions for invalid parameters.
*
* @see FreerailsSerializable
*/

Source Code

public interface SpeedAgainstTime extends FreerailsSerializable {
/**
* Returns the distance travelled at time t. The returned value, s,
* satisfies the following conditions:
* <ol>
* <li>s >= 0</li>
* <li>s <= getS()</li>
* <li>s = 0 if t = 0 </li>
* <li>s = getS() if t = getT()</li>
* </ol>
*
* @throws IllegalArgumentException
* iff t < 0 or t > getT()
* @return s
*/
double calcS(double t);
/**
* Returns the time taken to travel distance s. The returned value, t,
* satisfies the following conditions:
* <ol>
* <li>t >= 0</li>
* <li>t <= getT()</li>
* <li>t = 0 if s = 0 </li>
* <li>t = getT() if s = getS()</li>
* </ol>
*
* @throws IllegalArgumentException
* iff s < 0 or s > getS()
* @return t
*/
double calcT(double s);
/**
* @throws IllegalArgumentException
* iff t < 0 or t > getT()
*/
double calcV(double t);
/**
* @throws IllegalArgumentException
* iff t < 0 or t > getT()
*/
double calcA(double t);
/**
* @return The time taken to travel the distance given by getS().
*/
double getT();
/**
* @return The distance traveled during at time given by getT().
*/
double getS();
}

Schedule

Full name: jfreerails.world.train.Schedule

Documentation

/**
* Defines methods to access a train's schedule.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* Defines methods to access a train's schedule.
*
* @author Luke Lindsay
*
*/
public interface Schedule {
public static int PRIORITY_ORDERS = 0;
public static final int MAXIMUM_NUMBER_OF_ORDER = 6;
TrainOrdersModel getOrder(int i);
/** Returns the number of the order the train is currently carry out. */
int getOrderToGoto();
/**
* Returns the station number of the next station the train is scheduled to
* stop at.
*/
int getStationToGoto();
/** Returns the wagons to add at the next scheduled stop. */
ImInts getWagonsToAdd();
/** Returns the value for the autoconsist flag at the next scheduled stop. */
boolean autoConsist();
boolean hasPriorityOrders();
/**
* Returns number of non priority orders + number of priority orders.
*
* @return Number of orders.
*/
int getNumOrders();
int getNextScheduledOrder();
}

PathOnTiles

Full name: jfreerails.world.train.PathOnTiles

Documentation

/**
* An immutable class that stores a path made up of OneTileMoveVectors.
*
* @author Luke
*
*/

Source Code

/**
* An immutable class that stores a path made up of OneTileMoveVectors.
*
* @author Luke
*
*/
strictfp public class PathOnTiles implements FreerailsSerializable {
private static final long serialVersionUID = 3544386994122536753L;
private final ImPoint start;
private final ImList<Step> vectors;
/**
* @throws NullPointerException
* if null == start
* @throws NullPointerException
* if null == vectorsList
* @throws NullPointerException
* if null == vectorsList.get(i) for any i;
*/
public PathOnTiles(ImPoint start, List<Step> vectorsList) {
if (null == start)
throw new NullPointerException();
vectors = new ImList<Step>(vectorsList);
vectors.checkForNulls();
this.start = start;
}
/**
* @throws NullPointerException
* if null == start
* @throws NullPointerException
* if null == vectors
* @throws NullPointerException
* if null == vectors[i] for any i;
*/
public PathOnTiles(ImPoint start, Step... vectors) {
if (null == start)
throw new NullPointerException();
this.vectors = new ImList<Step>(vectors);
this.vectors.checkForNulls();
this.start = start;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof PathOnTiles))
return false;
final PathOnTiles pathOnTiles = (PathOnTiles) o;
if (!start.equals(pathOnTiles.start))
return false;
if (!vectors.equals(pathOnTiles.vectors))
return false;
return true;
}
/**
* Returns the distance you would travel if you walked the all the way along
* the path.
*/
public double getTotalDistance() {
return getDistance(vectors.size());
}
public double getDistance(int steps) {
double distanceSoFar = 0;
for (int i = 0; i < steps; i++) {
Step v = vectors.get(i);
distanceSoFar += v.getLength();
}
return distanceSoFar;
}
/**
* Returns the coordinates of the point you would be standing at if you
* walked the specified distance along the path from the start point.
*
* @throws IllegalArgumentException
* if distance < 0
* @throws IllegalArgumentException
* if distance > getLength()
*/
public ImPoint getPoint(double distance) {
if (0 > distance)
throw new IllegalArgumentException("distance:" + distance + " < 0");
int x = start.x * TILE_DIAMETER + TILE_DIAMETER / 2;
int y = start.y * TILE_DIAMETER + TILE_DIAMETER / 2;
double distanceSoFar = 0;
for (int i = 0; i < vectors.size(); i++) {
Step v = vectors.get(i);
distanceSoFar += v.getLength();
x += v.deltaX * TILE_DIAMETER;
y += v.deltaY * TILE_DIAMETER;
if (distanceSoFar == distance) {
return new ImPoint(x, y);
}
if (distanceSoFar > distance) {
double excess = distanceSoFar - distance;
x -= v.deltaX * TILE_DIAMETER * excess / v.getLength();
y -= v.deltaY * TILE_DIAMETER * excess / v.getLength();
return new ImPoint(x, y);
}
}
throw new IllegalArgumentException("distance > getLength()");
}
public ImPoint getStart() {
return start;
}
public Step getStep(int i) {
return vectors.get(i);
}
public PositionOnTrack getFinalPosition() {
int x = start.x;
int y = start.y;
for (int i = 0; i < vectors.size(); i++) {
Step v = vectors.get(i);
x += v.deltaX;
y += v.deltaY;
}
int i = vectors.size() - 1;
Step finalStep = vectors.get(i);
PositionOnTrack p = PositionOnTrack.createFacing(x, y, finalStep);
return p;
}
/**
* Returns the index of the step that takes the distance travelled over the
* specified distance.
*
* @throws IllegalArgumentException
* if distance < 0
* @throws IllegalArgumentException
* if distance > getLength()
*/
public int getStepIndex(int distance) {
if (0 > distance)
throw new IllegalArgumentException("distance < 0");
int distanceSoFar = 0;
for (int i = 0; i < vectors.size(); i++) {
Step v = vectors.get(i);
distanceSoFar += v.getLength();
if (distanceSoFar >= distance)
return i;
}
throw new IllegalArgumentException("distance > getLength()");
}
@Override
public int hashCode() {
return start.hashCode();
}
public int steps() {
return vectors.size();
}
public PathOnTiles addSteps(Step... newSteps) {
int oldLength = vectors.size();
Step[] newPath = new Step[oldLength + newSteps.length];
for (int i = 0; i < oldLength; i++) {
newPath[i] = vectors.get(i);
}
for (int i = 0; i < newSteps.length; i++) {
newPath[i + oldLength] = newSteps[i];
}
return new PathOnTiles(start, newPath);
}
/**
* Returns a FreerailsPathIterator that exposes a sub section of the path
* this object represents.
*
* @throws IllegalArgumentException
* if offset < 0
* @throws IllegalArgumentException
* if length <= 0
* @throws IllegalArgumentException
* if offset + length > getLength()
*
*/
public FreerailsPathIterator subPath(double offset, double length) {
if (offset < 0)
throw new IllegalArgumentException();
if (length <= 0)
throw new IllegalArgumentException();
if ((offset + length) > getTotalDistance())
throw new IllegalArgumentException(offset +" + "+ length+" > " +getTotalDistance());
final LinkedList<ImPoint> points = new LinkedList<ImPoint>();
ImPoint tile = getStart();
int tileX = tile.x;
int tileY = tile.y;
int distanceSoFar = 0;
for (int i = 0; i < vectors.size(); i++) {
if (distanceSoFar > offset + length) {
break;
}
if (distanceSoFar >= offset) {
int x = TILE_DIAMETER / 2 + TILE_DIAMETER * tileX;
int y = TILE_DIAMETER / 2 + TILE_DIAMETER * tileY;
points.add(new ImPoint(x, y));
}
Step v = vectors.get(i);
tileX += v.deltaX;
tileY += v.deltaY;
distanceSoFar += v.getLength();
}
ImPoint first = getPoint(offset);
if (points.size() == 0) {
points.addFirst(first);
} else if (!points.getFirst().equals(first)) {
points.addFirst(first);
}
ImPoint last = getPoint(offset + length);
if (!points.getLast().equals(last)) {
points.addLast(last);
}
return new FreerailsPathIterator() {
private static final long serialVersionUID = 1L;
int index = 0;
public boolean hasNext() {
return (index + 1) < points.size();
}
public void nextSegment(IntLine line) {
if (!hasNext()) {
throw new NoSuchElementException();
}
ImPoint a = points.get(index);
line.x1 = a.x;
line.y1 = a.y;
ImPoint b = points.get(index + 1);
line.x2 = b.x;
line.y2 = b.y;
index++;
}
};
}
public Iterator<ImPoint> tiles() {
return new Iterator<ImPoint>() {
int index = 0;
ImPoint next = start;
public boolean hasNext() {
return next != null;
}
public ImPoint next() {
if (next == null)
throw new NoSuchElementException();
ImPoint returnValue = next;
int x = next.x;
int y = next.y;
if (index < vectors.size()) {
Step s = vectors.get(index);
x += s.deltaX;
y += s.deltaY;
next = new ImPoint(x, y);
} else {
next = null;
}
index++;
return returnValue;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer(getClass().getName());
sb.append("{");
sb.append(start.x);
sb.append(", ");
sb.append(start.y);
for (int i = 0; i < vectors.size(); i++) {
sb.append(", ");
sb.append(vectors.get(i));
}
sb.append("}");
return sb.toString();
}
}

TrainPositionOnMap

Full name: jfreerails.world.train.TrainPositionOnMap

Documentation

/**
* This <b>immutable</b> class represents the position of a train as a String
* of points. There must be at least two points. The first point is the position
* of the front of the train; the last point is the position of the end of the
* train. Any intermediate points are positions of 'kinks' in the track.
*
* Coordinates are expressed in display coordinates relative to the map origin
* (as opposed to map squares).
*
*
* <p>
* Train positions can be combined and divided as illustrated below (notice what
* happens to the head and tail that are combined)
* </p>
* <table width="100%" border="0">
* <tr>
* <td>if</td>
* <td><code> a</code></td>
* <td><code>=</code></td>
* <td><code>{<strong>(10, 10)</strong>, (20,20), (30,30), (40,40) }</code></td>
* </tr>
* <tr>
* <td>and</td>
* <td><code> b</code></td>
* <td><code>=</code></td>
* <td><code>{(1,1), (4,4), (5,5), <strong>(10, 10)</strong>}</code></td>
* </tr>
* <tr>
* <td>then</td>
* <td><code>a.addToHead(b)</code></td>
* <td><code>=</code></td>
* <td><code>{(1,1), (4,4), (5,5), (20,20), (30,30), (40,40) }</code></td>
* </tr>
* <tr>
* <td>and</td>
* <td><code>b.addToTail(a)</code></td>
* <td><code>=</code></td>
* <td><code>{(1,1), (4,4), (5,5), (20,20), (30,30), (40,40) }</code></td>
* </tr>
* <tr>
* <td>and if</td>
* <td><code> c</code></td>
* <td><code>=</code></td>
* <td><code>{(1,1), (4,4), (5,5), (20,20), (30,30), (40,40) }</code></td>
* </tr>
* <tr>
* <td>then</td>
* <td><code>c.removeFromTail(a)</code></td>
* <td><code>=</code></td>
* <td><code>{(1,1), (4,4), (5,5), (10, 10)}</code></td>
* </tr>
* <tr>
* <td>and</td>
* <td><code>c.removeFromHead(b)</code></td>
* <td><code>=</code></td>
* <td><code>{(10, 10), (20,20), (30,30), (40,40) }</code></td>
* </tr>
* </table>
*
*
* @author Luke Lindsay 26-Oct-2002
*
*/

Source Code

/**
* This <b>immutable</b> class represents the position of a train as a String
* of points. There must be at least two points. The first point is the position
* of the front of the train; the last point is the position of the end of the
* train. Any intermediate points are positions of 'kinks' in the track.
*
* Coordinates are expressed in display coordinates relative to the map origin
* (as opposed to map squares).
*
*
* <p>
* Train positions can be combined and divided as illustrated below (notice what
* happens to the head and tail that are combined)
* </p>
* <table width="100%" border="0">
* <tr>
* <td>if</td>
* <td><code> a</code></td>
* <td><code>=</code></td>
* <td><code>{<strong>(10, 10)</strong>, (20,20), (30,30), (40,40) }</code></td>
* </tr>
* <tr>
* <td>and</td>
* <td><code> b</code></td>
* <td><code>=</code></td>
* <td><code>{(1,1), (4,4), (5,5), <strong>(10, 10)</strong>}</code></td>
* </tr>
* <tr>
* <td>then</td>
* <td><code>a.addToHead(b)</code></td>
* <td><code>=</code></td>
* <td><code>{(1,1), (4,4), (5,5), (20,20), (30,30), (40,40) }</code></td>
* </tr>
* <tr>
* <td>and</td>
* <td><code>b.addToTail(a)</code></td>
* <td><code>=</code></td>
* <td><code>{(1,1), (4,4), (5,5), (20,20), (30,30), (40,40) }</code></td>
* </tr>
* <tr>
* <td>and if</td>
* <td><code> c</code></td>
* <td><code>=</code></td>
* <td><code>{(1,1), (4,4), (5,5), (20,20), (30,30), (40,40) }</code></td>
* </tr>
* <tr>
* <td>then</td>
* <td><code>c.removeFromTail(a)</code></td>
* <td><code>=</code></td>
* <td><code>{(1,1), (4,4), (5,5), (10, 10)}</code></td>
* </tr>
* <tr>
* <td>and</td>
* <td><code>c.removeFromHead(b)</code></td>
* <td><code>=</code></td>
* <td><code>{(10, 10), (20,20), (30,30), (40,40) }</code></td>
* </tr>
* </table>
*
*
* @author Luke Lindsay 26-Oct-2002
*
*/
public class TrainPositionOnMap implements FreerailsSerializable {
public static final int CRASH_FRAMES_COUNT = 15;
private static final long serialVersionUID = 3979269144611010865L;
private final ImInts xpoints;
private final ImInts ypoints;
private final double speed, acceleration;
private final SpeedTimeAndStatus.TrainActivity activity;
private boolean crashSite = false;
public boolean isCrashSite() {
return crashSite;
}
public void setCrashSite(boolean isCrash) {
crashSite = isCrash;
}
private int frameCt = 1;
private int frame = 0;
public int getFrameCt() {
return frameCt;
}
public void incrementFramCt() {
if (frame > 0) {
incrementFrame();
frame = 0;
} else {
frame++;
}
}
public void incrementFrame() {
frameCt++;
}
@Override
public int hashCode() {
int result = 0;
// TODO is there are danger of overflow here?
for (int i = 0; i < xpoints.size(); i++) {
result = 29 * result + xpoints.get(i);
}
for (int i = 0; i < ypoints.size(); i++) {
result = 29 * result + ypoints.get(i);
}
return result;
}
@Override
public boolean equals(Object o) {
if (null == o) {
return false;
}
if (o == this) {
return true;
}
if (o instanceof TrainPositionOnMap) {
TrainPositionOnMap other = (TrainPositionOnMap) o;
int thisLength = this.getLength();
int otherLength = other.getLength();
if (thisLength == otherLength) {
FreerailsPathIterator path1;
FreerailsPathIterator path2;
IntLine line1 = new IntLine();
IntLine line2 = new IntLine();
path1 = other.path();
path2 = this.path();
while (path1.hasNext() && path2.hasNext()) {
path1.nextSegment(line1);
path2.nextSegment(line2);
if (line1.x1 != line2.x1 || line1.y1 != line2.y1
|| line1.x2 != line2.x2 || line1.y2 != line2.y2) {
return false;
}
}
if (path1.hasNext() || path2.hasNext()) {
return false;
}
return true;
}
return false;
}
return false;
}
public double calculateDistance() {
double distance = 0;
IntLine line = new IntLine();
FreerailsPathIterator path = this.path();
while (path.hasNext()) {
path.nextSegment(line);
int sumOfSquares = (line.x1 - line.x2) * (line.x1 - line.x2)
+ (line.y1 - line.y2) * (line.y1 - line.y2);
distance += Math.sqrt(sumOfSquares);
}
return distance;
}
public int getLength() {
return xpoints.size();
}
public ImInts getXPoints() {
return xpoints;
}
public ImInts getYPoints() {
return ypoints;
}
public int getX(int position) {
return xpoints.get(position);
}
public int getY(int position) {
return ypoints.get(position);
}
public FreerailsPathIterator path() {
return new SimplePathIteratorImpl(this.xpoints, this.ypoints);
}
public FreerailsPathIterator reversePath() {
int length = xpoints.size();
int[] reversed_xpoints = new int[length];
int[] reversed_ypoints = new int[length];
for (int i = 0; i < length; i++) {
reversed_xpoints[i] = xpoints.get(length - i - 1);
reversed_ypoints[i] = ypoints.get(length - i - 1);
}
return new SimplePathIteratorImpl(reversed_xpoints, reversed_ypoints);
}
public TrainPositionOnMap reverse() {
int length = xpoints.size();
int[] reversed_xpoints = new int[length];
int[] reversed_ypoints = new int[length];
for (int i = 0; i < length; i++) {
reversed_xpoints[i] = xpoints.get(length - i - 1);
reversed_ypoints[i] = ypoints.get(length - i - 1);
}
return new TrainPositionOnMap(reversed_xpoints, reversed_ypoints,
speed, acceleration, activity);
}
public TrainPositionOnMap(ImInts xs, ImInts ys) {
this.xpoints = xs;
this.ypoints = ys;
this.acceleration = 0d;
this.speed = 0d;
this.activity = SpeedTimeAndStatus.TrainActivity.READY;
}
private TrainPositionOnMap(int[] xs, int[] ys, double speed,
double acceleration, SpeedTimeAndStatus.TrainActivity activity) {
if (xs.length != ys.length) {
throw new IllegalArgumentException();
}
xpoints = new ImInts(xs);
ypoints = new ImInts(ys);
this.acceleration = acceleration;
this.speed = speed;
this.activity = activity;
}
public static TrainPositionOnMap createInstance(int[] xpoints, int[] ypoints) {
return new TrainPositionOnMap(xpoints, ypoints, 0d, 0d,
SpeedTimeAndStatus.TrainActivity.READY);
}
public TrainPositionOnMap addToHead(TrainPositionOnMap b) {
TrainPositionOnMap a = this;
return addBtoHeadOfA(b, a);
}
private TrainPositionOnMap addBtoHeadOfA(TrainPositionOnMap b,
TrainPositionOnMap a) {
if (aHeadEqualsBTail(a, b)) {
int newLength = a.getLength() + b.getLength() - 2;
int[] newXpoints = new int[newLength];
int[] newYpoints = new int[newLength];
int aLength = a.getLength();
int bLength = b.getLength();
// First copy the points from B
for (int i = 0; i < bLength - 1; i++) {
newXpoints[i] = b.getX(i);
newYpoints[i] = b.getY(i);
}
// Second copy the points from A.
for (int i = 1; i < aLength; i++) {
newXpoints[i + bLength - 2] = a.getX(i);
newYpoints[i + bLength - 2] = a.getY(i);
}
return new TrainPositionOnMap(newXpoints, newYpoints,
b.acceleration, b.speed, b.activity);
}
throw new IllegalArgumentException("Tried to add " + b.toString()
+ " to the head of " + a.toString());
}
public boolean canAddToHead(TrainPositionOnMap b) {
return aHeadEqualsBTail(this, b);
}
public TrainPositionOnMap addToTail(TrainPositionOnMap a) {
TrainPositionOnMap b = this;
return addBtoHeadOfA(b, a);
}
public boolean canAddToTail(TrainPositionOnMap b) {
return aHeadEqualsBTail(b, this);
}
public TrainPositionOnMap removeFromHead(TrainPositionOnMap b) {
if (headsAreEqual(this, b)) {
int newLength = this.getLength() - b.getLength() + 2;
int[] newXpoints = new int[newLength];
int[] newYpoints = new int[newLength];
int bLength = b.getLength();
// copy head from b
int bHeadPosition = b.getLength() - 1;
newXpoints[0] = b.getX(bHeadPosition);
newYpoints[0] = b.getY(bHeadPosition);
// Copy rest from this
for (int i = 1; i < newLength; i++) {
int position = bLength + i - 2;
newXpoints[i] = this.getX(position);
newYpoints[i] = this.getY(position);
}
return new TrainPositionOnMap(newXpoints, newYpoints, speed,
acceleration, activity);
}
throw new IllegalArgumentException();
}
public boolean canRemoveFromHead(TrainPositionOnMap b) {
if (headsAreEqual(this, b)) {
FreerailsPathIterator path = b.path();
int i = 0;
IntLine line = new IntLine();
while (path.hasNext()) {
path.nextSegment(line);
if (this.getX(i) != line.x1 || this.getY(i) != line.y1) {
return false;
}
i++;
}
return true;
}
return false;
}
public TrainPositionOnMap removeFromTail(TrainPositionOnMap b) {
if (tailsAreEqual(this, b)) {
int newLength = this.getLength() - b.getLength() + 2;
int[] newXpoints = new int[newLength];
int[] newYpoints = new int[newLength];
// Copy from this
for (int i = 0; i < newLength - 1; i++) {
newXpoints[i] = this.getX(i);
newYpoints[i] = this.getY(i);
}
// Copy tail from b
newXpoints[newLength - 1] = b.getX(0);
newYpoints[newLength - 1] = b.getY(0);
return new TrainPositionOnMap(newXpoints, newYpoints, speed,
acceleration, activity);
}
throw new IllegalArgumentException();
}
public boolean canRemoveFromTail(TrainPositionOnMap b) {
if (tailsAreEqual(this, b)) {
FreerailsPathIterator path = b.reversePath();
int i = this.getLength() - 1;
IntLine line = new IntLine();
while (path.hasNext()) {
path.nextSegment(line);
if (this.getX(i) != line.x1 || this.getY(i) != line.y1) {
return false;
}
i--;
}
return true;
}
return false;
}
public static TrainPositionOnMap createInSameDirectionAsPath(
FreerailsPathIterator path) {
return createInSameDirectionAsPath(path, 0d, 0d,
SpeedTimeAndStatus.TrainActivity.READY);
}
public static TrainPositionOnMap createInSameDirectionAsPath(
FreerailsPathIterator path, double speed, double acceleration,
SpeedTimeAndStatus.TrainActivity activity) {
IntArray xPointsIntArray = new IntArray();
IntArray yPointsIntArray = new IntArray();
IntLine line = new IntLine();
int i = 0;
while (path.hasNext()) {
path.nextSegment(line);
xPointsIntArray.add(i, line.x1);
yPointsIntArray.add(i, line.y1);
i++;
if (i > 10000) {
throw new IllegalStateException(
"The TrainPosition has more than 10,000 points, which suggests that something is wrong.");
}
}
xPointsIntArray.add(i, line.x2);
yPointsIntArray.add(i, line.y2);
int[] xPoints;
int[] yPoints;
xPoints = xPointsIntArray.toArray();
yPoints = yPointsIntArray.toArray();
return new TrainPositionOnMap(xPoints, yPoints, speed, acceleration,
activity);
}
public static boolean headsAreEqual(TrainPositionOnMap a,
TrainPositionOnMap b) {
int aHeadX = a.getX(0);
int aHeadY = a.getY(0);
int bHeadX = b.getX(0);
int bHeadY = b.getY(0);
if (aHeadX == bHeadX && aHeadY == bHeadY) {
return true;
}
return false;
}
public static boolean tailsAreEqual(TrainPositionOnMap a,
TrainPositionOnMap b) {
int aTailX = a.getX(a.getLength() - 1);
int aTailY = a.getY(a.getLength() - 1);
int bTailX = b.getX(b.getLength() - 1);
int bTailY = b.getY(b.getLength() - 1);
if (aTailX == bTailX && aTailY == bTailY) {
return true;
}
return false;
}
public static boolean aHeadEqualsBTail(TrainPositionOnMap a,
TrainPositionOnMap b) {
int aHeadX = a.getX(0);
int aHeadY = a.getY(0);
int bTailX = b.getX(b.getLength() - 1);
int bTailY = b.getY(b.getLength() - 1);
if (aHeadX == bTailX && aHeadY == bTailY) {
return true;
}
return false;
}
public static boolean bHeadEqualsATail(TrainPositionOnMap a,
TrainPositionOnMap b) {
return aHeadEqualsBTail(b, a);
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("TrainPosition {");
for (int i = 0; i < xpoints.size(); i++) {
sb.append("(");
sb.append(xpoints.get(i));
sb.append(", ");
sb.append(ypoints.get(i));
sb.append("), ");
}
sb.append("}");
return sb.toString();
}
public double getAcceleration() {
return acceleration;
}
public SpeedTimeAndStatus.TrainActivity getActivity() {
return activity;
}
public double getSpeed() {
return speed;
}
}

WagonType

Full name: jfreerails.world.train.WagonType

Documentation

/**
* This class represents a wagon type, for example 'goods wagon'. It
* encapsulates the properties of a wagon that are common to all wagons of the
* same type.
*
* @author Luke
*
*/

Source Code

/**
* This class represents a wagon type, for example 'goods wagon'. It
* encapsulates the properties of a wagon that are common to all wagons of the
* same type.
*
* @author Luke
*
*/
public class WagonType implements FreerailsSerializable {
private static final long serialVersionUID = 3906368233710826292L;
public static final int BULK_FREIGHT = 4;
public static final int ENGINE = 5;
public static final int FAST_FREIGHT = 2;
public static final int MAIL = 0;
public static final int NUMBER_OF_CATEGORIES = 6;
public static final int PASSENGER = 1;
public static final int SLOW_FREIGHT = 3;
public static final int UNITS_OF_CARGO_PER_WAGON = 40;
private final int typeCategory;
private final String typeName;
public WagonType(String name, int category) {
typeName = name;
typeCategory = category;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof WagonType))
return false;
WagonType other = (WagonType) obj;
return other.typeCategory == this.typeCategory
&& other.typeName.equals(typeName);
}
public int getCategory() {
return typeCategory;
}
public String getName() {
return typeName;
}
@Override
public int hashCode() {
int result;
result = typeCategory;
result = 29 * result + typeName.hashCode();
return result;
}
@Override
public String toString() {
return typeName;
}
}

SimplePathIteratorImpl

Full name: jfreerails.world.train.SimplePathIteratorImpl

Documentation

/**
* Exposes a path stored as an array of x points and an array of y points.
*
* @author Luke
*/

Source Code

/**
* Exposes a path stored as an array of x points and an array of y points.
*
* @author Luke
*/
public class SimplePathIteratorImpl implements FreerailsPathIterator {
private static final long serialVersionUID = 3618420406261003576L;
private final ImInts x;
private final ImInts y;
private int position = 0;
public SimplePathIteratorImpl(ImInts xpoints, ImInts ypoints) {
x = xpoints;
y = ypoints;
if (x.size() != y.size()) {
throw new IllegalArgumentException(
"The array length of the array must be even");
}
}
public SimplePathIteratorImpl( /* =const */
int[] xpoints, /* =const */
int[] ypoints) {
x = new ImInts(xpoints);
y = new ImInts(ypoints); // defensive copy.
if (x.size() != y.size()) {
throw new IllegalArgumentException(
"The array length of the array must be even");
}
}
public void nextSegment(IntLine line) {
if (hasNext()) {
line.x1 = x.get(position);
line.y1 = y.get(position);
line.x2 = x.get(position + 1);
line.y2 = y.get(position + 1);
position++;
} else {
throw new NoSuchElementException();
}
}
public boolean hasNext() {
return (position + 1) < x.size();
}
}

PathWalkerImpl

Full name: jfreerails.world.train.PathWalkerImpl

Documentation

/**
* PathWalker that walks the path exposed by a FreerailsPathIterator.
*
* @author Luke
*/

Source Code

/**
* PathWalker that walks the path exposed by a FreerailsPathIterator.
*
* @author Luke
*/
public class PathWalkerImpl implements PathWalker {
private static final long serialVersionUID = 4050204158701155639L;
private final FreerailsPathIterator it;
/**
* current segment of the path we are on.
*/
private final IntLine currentSegment = new IntLine();
private double distanceAlongCurrentSegment = 0;
private double distanceOfThisStepRemaining = 0;
private boolean beforeFirst = true;
private int lastX;
private int lastY;
public PathWalkerImpl(FreerailsPathIterator i) {
it = i;
}
/**
* @return true if we still have more of the current segment, or more
* segments left.
*/
public boolean canStepForward() {
if (currentSegment.getLength() > distanceAlongCurrentSegment) {
return true;
} else if (it.hasNext()) {
return true;
} else {
return false;
}
}
/**
* Specify the distance this PathWalker is to progress along the current
* step.
*/
public void stepForward(double distance) {
distanceOfThisStepRemaining += distance;
}
/**
* @return true if there is still some distance to go along this path
*/
public boolean hasNext() {
if (0 == distanceOfThisStepRemaining) {
return false;
} else if (distanceAlongCurrentSegment < currentSegment.getLength()) {
return true;
} else if (it.hasNext()) {
return true;
} else {
return false;
}
}
public void nextSegment(IntLine line) {
if (!hasNext()) {
throw new NoSuchElementException();
}
// If we are at the end of the current segment, start a new one.
if (currentSegment.getLength() <= distanceAlongCurrentSegment) {
startNewSegment(line);
} else {
startInMiddleOfSegment(line);
}
double remainingDistanceAlongCurrentSegment = currentSegment
.getLength()
- distanceAlongCurrentSegment;
if (distanceOfThisStepRemaining > remainingDistanceAlongCurrentSegment) {
endAtSegmentEnd(line, remainingDistanceAlongCurrentSegment);
} else {
endInMiddleOfSegment(line);
}
/*
* Sanity check: the first point of the last line should equal the
* second point of the current line.
*
*/
if (!beforeFirst) {
if (line.x1 != this.lastX) {
throw new IllegalStateException();
}
if (line.y1 != this.lastY) {
throw new IllegalStateException();
}
}
this.lastX = line.x2;
this.lastY = line.y2;
beforeFirst = false;
return;
}
private void endInMiddleOfSegment(IntLine line) {
distanceAlongCurrentSegment += distanceOfThisStepRemaining;
distanceOfThisStepRemaining = 0;
line.x2 = getCoordinateOnSegment(distanceAlongCurrentSegment,
currentSegment.x1, currentSegment.x2);
line.y2 = getCoordinateOnSegment(distanceAlongCurrentSegment,
currentSegment.y1, currentSegment.y2);
}
private void endAtSegmentEnd(IntLine line,
double remainingDistanceAlongCurrentSegment) {
line.x2 = this.currentSegment.x2;
line.y2 = this.currentSegment.y2;
this.distanceOfThisStepRemaining -= remainingDistanceAlongCurrentSegment;
distanceAlongCurrentSegment = this.currentSegment.getLength();
}
private void startInMiddleOfSegment(IntLine line) {
line.x1 = getCoordinateOnSegment(distanceAlongCurrentSegment,
currentSegment.x1, currentSegment.x2);
line.y1 = getCoordinateOnSegment(distanceAlongCurrentSegment,
currentSegment.y1, currentSegment.y2);
}
private void startNewSegment(IntLine line) {
it.nextSegment(currentSegment);
distanceAlongCurrentSegment = 0;
line.x1 = this.currentSegment.x1;
line.y1 = this.currentSegment.y1;
}
private int getCoordinateOnSegment(double distanceAlongSegment,
int coordinate1, int coordinate2) {
double segmentLength = this.currentSegment.getLength();
double delta = 0;
if (0 != segmentLength) {
delta = (coordinate2 - coordinate1) * distanceAlongSegment
/ segmentLength;
}
return coordinate1 + (int) delta;
}
}

ConstAcc

Full name: jfreerails.world.train.ConstAcc

Documentation

/**
* Represents motion under constant acceleration, providing methods to calculate position, velocity, time, and other kinematic properties.
* This class encapsulates the parameters of constant acceleration motion (initial velocity, acceleration, final time, and final position)
* and includes utility methods to compute derived values based on time or displacement.
*
* @author John Doe
* @since 1.0
*
* @see FreerailsSerializable
* @see SpeedAgainstTime
*/

Source Code

strictfp public class ConstAcc implements FreerailsSerializable,
SpeedAgainstTime {
private static final long serialVersionUID = -2180666310811530761L;
public static final ConstAcc STOPPED = new ConstAcc(0, 0, 0, 0);
public static ConstAcc uas(double u, double a, double s) {
double t = calcT(u, a, s);
return new ConstAcc(a, t, u, s);
}
private static double calcT(double u, double a, double s) {
// Note, Utils.solveQuadratic throws an exception if a == 0
return a == 0 ? s / u : Utils.solveQuadratic(a * 0.5d, u, -s);
}
public static ConstAcc uat(double u, double a, double t) {
double s = u * t + a * t * t / 2;
return new ConstAcc(a, t, u, s);
}
private final double u, a, finalS, finalT;
private ConstAcc(double a, double t, double u, double s) {
this.a = a;
this.finalT = t;
this.u = u;
this.finalS = s;
}
public double calcS(double t) {
if(t == finalT) return finalS;
validateT(t);
double ds = u * t + a * t * t / 2;
ds = Math.min(ds, finalS);
return ds;
}
public double calcT(double s) {
if(s == finalS ) return finalT;
if(s < 0 || s > this.finalS )
throw new IllegalArgumentException(s+" < 0 || "+s+" > "+finalS );
double returnValue = calcT(u, a, s);
returnValue = Math.min(returnValue, finalT);
return returnValue;
}
public double calcV(double t) {
validateT(t);
return u + a * t;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ConstAcc))
return false;
final ConstAcc constAcc = (ConstAcc) o;
if (a != constAcc.a)
return false;
if (finalT != constAcc.finalT)
return false;
if (u != constAcc.u)
return false;
return true;
}
public double calcA(double t) {
validateT(t);
return a;
}
public double getT() {
return finalT;
}
public double getS() {
return finalS;
}
@Override
public int hashCode() {
int result;
long temp;
temp = u != +0.0d ? Double.doubleToLongBits(u) : 0l;
result = (int) (temp ^ (temp >>> 32));
temp = a != +0.0d ? Double.doubleToLongBits(a) : 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
temp = finalT != +0.0d ? Double.doubleToLongBits(finalT) : 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
return result;
}
private void validateT(double t){
if(t < 0 || t > finalT)
throw new IllegalArgumentException("("+t+" < 0 || "+t+" > "+finalT+")");
}
@Override
public String toString() {
String str = "ConstAcc [a=" + a + ", u=" + u + ", dt=" + finalT + "]";
return str;
}
}

TrainOrdersModel

Full name: jfreerails.world.train.TrainOrdersModel

Documentation

/**
* This class encapsulates the orders for a train.
*
* @author Luke
*/

Source Code

/**
* This class encapsulates the orders for a train.
*
* @author Luke
*/
public class TrainOrdersModel implements FreerailsSerializable {
private static final long serialVersionUID = 3616453397155559472L;
private static final int MAXIMUM_NUMBER_OF_WAGONS = 6;
public final boolean waitUntilFull;
public final boolean autoConsist;
/** The wagon types to add; if null, then no change.*/
public final ImInts consist;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TrainOrdersModel))
return false;
final TrainOrdersModel trainOrdersModel = (TrainOrdersModel) o;
if (autoConsist != trainOrdersModel.autoConsist)
return false;
if (stationId != trainOrdersModel.stationId)
return false;
if (waitUntilFull != trainOrdersModel.waitUntilFull)
return false;
if (consist != null ? !consist.equals(trainOrdersModel.consist)
: trainOrdersModel.consist != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = (waitUntilFull ? 1 : 0);
result = 29 * result + (autoConsist ? 1 : 0);
result = 29 * result + (consist != null ? consist.hashCode() : 0);
result = 29 * result + stationId;
return result;
}
public final int stationId; // The number of the station to goto.
public TrainOrdersModel(int station, ImInts newConsist, boolean wait,
boolean auto) {
// If there are no wagons, set wait = false.
wait = (null == newConsist || 0 == newConsist.size()) ? false : wait;
this.waitUntilFull = wait;
this.consist = newConsist;
this.stationId = station;
this.autoConsist = auto;
}
/**
* @return either (1) an array of cargo type ids or (2) null to represent
* 'no change'.
*/
public ImInts getConsist() {
return this.consist;
}
public int getStationID() {
return stationId;
}
public boolean isNoConsistChange() {
return null == consist;
}
public boolean getWaitUntilFull() {
return waitUntilFull;
}
public boolean orderHasWagons() {
return null != consist && 0 != consist.size();
}
public boolean hasLessThanMaximumNumberOfWagons() {
return null == consist || consist.size() < MAXIMUM_NUMBER_OF_WAGONS;
}
public boolean isAutoConsist() {
return autoConsist;
}
}

SpeedTimeAndStatus

Full name: jfreerails.world.train.SpeedTimeAndStatus

Documentation

/**
* Stores the speed and status of a train immediately after an instant of time.
*
* @author Luke
*
*/

Source Code

/**
* Stores the speed and status of a train immediately after an instant of time.
*
* @author Luke
*
*/
public class SpeedTimeAndStatus implements FreerailsSerializable {
private static final long serialVersionUID = 1L;
public enum TrainActivity {
STOPPED_AT_STATION, READY, WAITING_FOR_FULL_LOAD, STOPPED_AT_SIGNAL, CRASHED, NEEDS_UPDATING
}
public final double dt;
public final double speed;
public final double acceleration;
public final double s;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof SpeedTimeAndStatus))
return false;
final SpeedTimeAndStatus speedTimeAndStatus = (SpeedTimeAndStatus) o;
if (acceleration != speedTimeAndStatus.acceleration)
return false;
if (dt != speedTimeAndStatus.dt)
return false;
if (s != speedTimeAndStatus.s)
return false;
if (speed != speedTimeAndStatus.speed)
return false;
if (activity != null ? !activity.equals(speedTimeAndStatus.activity)
: speedTimeAndStatus.activity != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
long temp;
temp = dt != +0.0d ? Double.doubleToLongBits(dt) : 0l;
result = (int) (temp ^ (temp >>> 32));
temp = speed != +0.0d ? Double.doubleToLongBits(speed) : 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
temp = acceleration != +0.0d ? Double.doubleToLongBits(acceleration)
: 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
temp = s != +0.0d ? Double.doubleToLongBits(s) : 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
result = 29 * result + (activity != null ? activity.hashCode() : 0);
return result;
}
private final TrainActivity activity;
SpeedTimeAndStatus(double acceleration, TrainActivity activity, double dt,
double s, double speed) {
if (dt < 0)
throw new IllegalArgumentException(String.valueOf(dt));
this.acceleration = acceleration;
this.activity = activity;
this.dt = dt;
this.s = s;
this.speed = speed;
}
public TrainActivity getActivity() {
return activity;
}
}

CompositeSpeedAgainstTime

Full name: jfreerails.world.train.CompositeSpeedAgainstTime

Documentation

/**
* Represents a composite speed-time relationship composed of multiple {@link SpeedAgainstTime} segments.
* This class aggregates individual speed-time data to compute overall duration, distance, and
* instantaneous values (speed, acceleration) at any given time. It provides methods to calculate
* cumulative distance, time, and state information based on the combined segments.
*
* @author [Your Name]
* @see SpeedAgainstTime
* @see Activity
*/

Source Code

public class CompositeSpeedAgainstTime implements Activity<SpeedTimeAndStatus>,
SpeedAgainstTime {
private static final long serialVersionUID = 3146586143114534610L;
private final ImList<SpeedAgainstTime> values;
private final double finalT, finalS;
public CompositeSpeedAgainstTime(SpeedAgainstTime... accs) {
values = new ImList<SpeedAgainstTime>(accs);
values.checkForNulls();
double tempDuration = 0, tempTotalDistance = 0;
for (int i = 0; i < accs.length; i++) {
tempDuration += accs[i].getT();
tempTotalDistance += accs[i].getS();
}
finalT = tempDuration;
finalS = tempTotalDistance;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof CompositeSpeedAgainstTime))
return false;
final CompositeSpeedAgainstTime compositeSpeedAgainstTime = (CompositeSpeedAgainstTime) o;
if (finalT != compositeSpeedAgainstTime.finalT)
return false;
if (finalS != compositeSpeedAgainstTime.finalS)
return false;
if (!values.equals(compositeSpeedAgainstTime.values))
return false;
return true;
}
@Override
public int hashCode() {
int result;
long temp;
result = values.hashCode();
temp = finalT != +0.0d ? Double.doubleToLongBits(finalT) : 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
temp = finalS != +0.0d ? Double.doubleToLongBits(finalS)
: 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
return result;
}
public double duration() {
return finalT;
}
public SpeedTimeAndStatus getState(final double dt) {
checkT(dt);
double acceleration;
SpeedTimeAndStatus.TrainActivity activity = SpeedTimeAndStatus.TrainActivity.READY;
double s = 0;
double speed;
TandI tai = getIndex(dt);
SpeedAgainstTime acc = values.get(tai.i);
speed = acc.calcV(tai.offset);
acceleration = acc.calcA(tai.offset);
s = acc.calcS(tai.offset);
return new SpeedTimeAndStatus(acceleration, activity, dt, s, speed);
}
public double calcS(double t) {
if(t == this.finalT) return this.finalS;
checkT(t);
TandI tai = getIndex(t);
double s = 0;
for (int i = 0; i < tai.i; i++) {
SpeedAgainstTime acc = values.get(i);
s += acc.getS();
}
SpeedAgainstTime acc = values.get(tai.i);
if(tai.offset >= acc.getT()){
//Note, it is possible for tai.offset > acc.getT()
//even though we called checkT(t) above
s += acc.getS();
}else{
s += acc.calcS(tai.offset);
}
return s;
}
public double calcT(double s) {
if(s == this.finalS) return this.finalT;
if (s > finalS)
throw new IllegalArgumentException(String.valueOf(s));
double sSoFar = 0;
double tSoFar = 0;
int i = 0;
SpeedAgainstTime acc = values.get(i);
while ((sSoFar + acc.getS()) < s) {
sSoFar += acc.getS();
tSoFar += acc.getT();
i++;
acc = values.get(i);
}
double sOffset = s - sSoFar;
if(sOffset >= acc.getS()){
tSoFar += acc.getT();
}else{
tSoFar += acc.calcT(sOffset);
}
return tSoFar;
}
public double calcV(double t) {
checkT(t);
TandI tai = getIndex(t);
SpeedAgainstTime acc = values.get(tai.i);
return acc.calcV(tai.offset);
}
public double calcA(double t) {
checkT(t);
TandI tai = getIndex(t);
SpeedAgainstTime acc = values.get(tai.i);
return acc.calcA(tai.offset);
}
public double getT() {
return finalT;
}
public double getS() {
return finalS;
}
private TandI getIndex(double t) {
checkT(t);
double tSoFar = 0;
for (int i = 0; i < values.size(); i++) {
SpeedAgainstTime acc = values.get(i);
if (t <= (tSoFar + acc.getT())) {
double offset = t - tSoFar;
return new TandI(i, offset);
}
tSoFar += acc.getT();
}
// Should never happen since we call checkT() above!
throw new IllegalStateException(String.valueOf(t));
}
/** Used to enable 2 values to be returned from the method getIndex(double t) */
private static class TandI {
final double offset;
final int i;
TandI(int i, double t) {
this.i = i;
this.offset = t;
}
}
void checkT(double t) {
if (t < 0d || t > finalT)
throw new IllegalArgumentException("t="+t+", but duration="+finalT);
}
}

ImmutableSchedule

Full name: jfreerails.world.train.ImmutableSchedule

Documentation

/**
* A Schedule that is immutable.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* A Schedule that is immutable.
*
* @author Luke Lindsay
*
*/
public class ImmutableSchedule implements Schedule, FreerailsSerializable {
private static final long serialVersionUID = 3977858458324318264L;
private final ImList<TrainOrdersModel> orders;
private final int nextScheduledOrder;
@Override
public int hashCode() {
int result;
result = nextScheduledOrder;
result = 29 * result + (hasPriorityOrders ? 1 : 0);
return result;
}
private final boolean hasPriorityOrders;
public ImmutableSchedule(TrainOrdersModel[] orders, int gotoStation,
boolean hasPriorityOrders) {
this.orders = new ImList<TrainOrdersModel>(orders);
this.nextScheduledOrder = gotoStation;
this.hasPriorityOrders = hasPriorityOrders;
}
public TrainOrdersModel getOrder(int i) {
return orders.get(i);
}
public int getOrderToGoto() {
return hasPriorityOrders ? 0 : nextScheduledOrder;
}
public int getStationToGoto() {
int orderToGoto = getOrderToGoto();
if (-1 == orderToGoto) {
return -1;
}
TrainOrdersModel order = orders.get(orderToGoto);
return order.getStationID();
}
public ImInts getWagonsToAdd() {
TrainOrdersModel order = orders.get(getOrderToGoto());
return order.consist;
}
public boolean hasPriorityOrders() {
return hasPriorityOrders;
}
public int getNumOrders() {
return orders.size();
}
public int getNextScheduledOrder() {
return this.nextScheduledOrder;
}
public boolean stopsAtStation(int stationNumber) {
for (int i = 0; i < this.getNumOrders(); i++) {
TrainOrdersModel order = this.getOrder(i);
if (order.getStationID() == stationNumber) {
return true;
}
}
return false;
}
@Override
public boolean equals(Object o) {
if (o instanceof ImmutableSchedule) {
ImmutableSchedule test = (ImmutableSchedule) o;
return this.hasPriorityOrders == test.hasPriorityOrders
&& this.nextScheduledOrder == test.nextScheduledOrder
&& this.orders.equals(test.orders);
}
return false;
}
public boolean autoConsist() {
TrainOrdersModel order = orders.get(getOrderToGoto());
return order.autoConsist;
}
}

EngineType

Full name: jfreerails.world.train.EngineType

Documentation

/**
* This class represents an engine type, for example 'Grass Hopper'. It
* encapsulates the properties that are common to all engines of the same type.
*
* @author Luke
*
*/

Source Code

/**
* This class represents an engine type, for example 'Grass Hopper'. It
* encapsulates the properties that are common to all engines of the same type.
*
* @author Luke
*
*/
final public class EngineType implements FreerailsSerializable {
private static final long serialVersionUID = 3617014130905592630L;
private final String engineTypeName;
private final Money maintenance;
private final int maxSpeed; // speed in mph
private final int powerAtDrawbar;
private final Money price;
public EngineType(String name, int power, Money m, int speed) {
engineTypeName = name;
powerAtDrawbar = power;
price = m;
maxSpeed = speed;
maintenance = new Money(0);
}
public EngineType(String name, int power, Money m, int speed, Money maint) {
engineTypeName = name;
powerAtDrawbar = power;
price = m;
maxSpeed = speed;
maintenance = maint;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof EngineType))
return false;
EngineType other = (EngineType) obj;
return engineTypeName.equals(other.engineTypeName)
&& powerAtDrawbar == other.powerAtDrawbar && price.equals(other.price)
&& maintenance.equals(other.maintenance)
&& maxSpeed == other.maxSpeed;
}
public String getEngineTypeName() {
return engineTypeName;
}
public Money getMaintenance() {
return maintenance;
}
public int getMaxSpeed() {
return maxSpeed;
}
public int getPowerAtDrawbar() {
return powerAtDrawbar;
}
public Money getPrice() {
return price;
}
@Override
public int hashCode() {
int result;
result = powerAtDrawbar;
result = 29 * result + engineTypeName.hashCode();
result = 29 * result + price.hashCode();
result = 29 * result + maintenance.hashCode();
result = 29 * result + maxSpeed;
return result;
}
@Override
public String toString() {
return engineTypeName;
}
}

MutableSchedule

Full name: jfreerails.world.train.MutableSchedule

Documentation

/**
* This class represents a train's schedule. That is, which stations that the
* train should visit and what wagons the engine should pull.
*
* @author lindsal
*/

Source Code

/**
* This class represents a train's schedule. That is, which stations that the
* train should visit and what wagons the engine should pull.
*
* @author lindsal
*/
public class MutableSchedule implements Schedule {
/**
* Vector of TrainOrdersModel.
*/
private final Vector<TrainOrdersModel> orders = new Vector<TrainOrdersModel>();
private int nextScheduledOrder = -1;
/**
* Whether the train should ignore the stationToGoto and goto the first
* station in the list.
*/
private boolean hasPriorityOrders = false;
public MutableSchedule() {
}
public MutableSchedule(ImmutableSchedule s) {
nextScheduledOrder = s.getNextScheduledOrder();
hasPriorityOrders = s.hasPriorityOrders();
for (int i = 0; i < s.getNumOrders(); i++) {
orders.add(s.getOrder(i));
}
}
public ImmutableSchedule toImmutableSchedule() {
TrainOrdersModel[] ordersArray = new TrainOrdersModel[orders.size()];
for (int i = 0; i < ordersArray.length; i++) {
ordersArray[i] = orders.get(i);
}
return new ImmutableSchedule(ordersArray, this.nextScheduledOrder,
this.hasPriorityOrders);
}
public void setPriorityOrders(TrainOrdersModel order) {
if (hasPriorityOrders) {
// Replace existing priority orders.
orders.set(PRIORITY_ORDERS, order);
} else {
// Insert priority orders at position 0;
hasPriorityOrders = true;
orders.add(PRIORITY_ORDERS, order);
nextScheduledOrder++;
}
}
/**
* Removes the order at the specified position.
*/
public void removeOrder(int orderNumber) {
if (PRIORITY_ORDERS == orderNumber && hasPriorityOrders) {
// If we are removing the priority stop.
hasPriorityOrders = false;
}
orders.remove(orderNumber);
/* shift current station down */
if (nextScheduledOrder > orderNumber) {
nextScheduledOrder--;
}
if (orders.size() <= nextScheduledOrder) {
nextScheduledOrder = firstScheduleStop();
}
if (0 == numberOfScheduledStops()) {
nextScheduledOrder = -1;
}
}
private int firstScheduleStop() {
return hasPriorityOrders ? 1 : 0;
}
private int numberOfScheduledStops() {
return orders.size() - firstScheduleStop();
}
/**
* Inserts an order at the specified position. Note you must call
* setPriorityOrders() to set the priority orders.
*/
public void addOrder(int orderNumber, TrainOrdersModel order) {
orders.add(orderNumber, order);
if (nextScheduledOrder >= orderNumber) {
nextScheduledOrder++;
}
if (-1 == nextScheduledOrder && 0 < numberOfScheduledStops()) {
nextScheduledOrder = firstScheduleStop();
}
}
public int addOrder(TrainOrdersModel order) {
if (!canAddOrder()) {
throw new IllegalStateException();
}
int newOrderNumber = orders.size();
addOrder(newOrderNumber, order);
return newOrderNumber;
}
public void setOrder(int orderNumber, TrainOrdersModel order) {
if (orderNumber >= orders.size()) {
orders.add(order);
} else {
orders.set(orderNumber, order);
}
}
public TrainOrdersModel getOrder(int i) {
return orders.get(i);
}
/** Returns the number of the order the train is currently carry out. */
public int getOrderToGoto() {
return nextScheduledOrder;
}
public void setOrderToGoto(int i) {
if (i < 0 || i >= orders.size()) {
throw new IllegalArgumentException(String.valueOf(i));
}
nextScheduledOrder = i;
}
/**
* Returns the station number of the next station the train is scheduled to
* stop at.
*/
public int getStationToGoto() {
return orders.get(nextScheduledOrder).getStationID();
}
/** Returns the wagons to add at the next scheduled stop. */
public ImInts getWagonsToAdd() {
return orders.get(nextScheduledOrder).getConsist();
}
/**
* If there are no priority orders, sets the station to goto to the next
* station in the list of orders or if there are no more stations, the first
* station in the list. If priority orders are set, the priority orders
* orders are removed from the schedule and the goto station is not changed.
*/
public void gotoNextStation() {
if (hasPriorityOrders) {
if (nextScheduledOrder != PRIORITY_ORDERS) {
removeOrder(PRIORITY_ORDERS);
return;
}
}
nextScheduledOrder++;
if (orders.size() <= nextScheduledOrder) {
nextScheduledOrder = 0;
}
}
public boolean hasPriorityOrders() {
return this.hasPriorityOrders;
}
/**
* Returns number of non priority orders + number of priority orders.
*
* @return Number of orders.
*/
public int getNumOrders() {
return orders.size();
}
public boolean canPullUp(int orderNumber) {
boolean isAlreadyAtTop = 0 == orderNumber;
boolean isPriorityOrdersAbove = (orderNumber == 1 && this.hasPriorityOrders);
return !isAlreadyAtTop && !isPriorityOrdersAbove;
}
public boolean canPushDown(int orderNumber) {
boolean isOrderPriorityOrders = (orderNumber == 0 && this.hasPriorityOrders);
boolean isAlreadyAtBottom = orderNumber == this.orders.size() - 1;
return !isOrderPriorityOrders && !isAlreadyAtBottom;
}
public void pullUp(int orderNumber) {
if (!canPullUp(orderNumber)) {
throw new IllegalArgumentException(String.valueOf(orderNumber));
}
boolean isGoingToThisStation = getOrderToGoto() == orderNumber;
TrainOrdersModel order = getOrder(orderNumber);
removeOrder(orderNumber);
addOrder(orderNumber - 1, order);
if (isGoingToThisStation) {
setOrderToGoto(orderNumber - 1);
}
}
public void pushDown(int orderNumber) {
if (!canPushDown(orderNumber)) {
throw new IllegalArgumentException(String.valueOf(orderNumber));
}
boolean isGoingToThisStation = getOrderToGoto() == orderNumber;
TrainOrdersModel order = getOrder(orderNumber);
removeOrder(orderNumber);
addOrder(orderNumber + 1, order);
if (isGoingToThisStation) {
setOrderToGoto(orderNumber + 1);
}
}
public boolean canAddOrder() {
int max = hasPriorityOrders ? MAXIMUM_NUMBER_OF_ORDER + 1
: MAXIMUM_NUMBER_OF_ORDER;
return max > getNumOrders();
}
public boolean canSetGotoStation(int orderNumber) {
return !(orderNumber == 0 && hasPriorityOrders);
}
public int getNextScheduledOrder() {
return this.nextScheduledOrder;
}
public void removeAllStopsAtStation(int stationNumber) {
int i = 0;
while (i < this.getNumOrders()) {
TrainOrdersModel order = this.getOrder(i);
if (order.getStationID() == stationNumber) {
this.removeOrder(i);
} else {
i++;
}
}
}
public boolean autoConsist() {
return orders.get(nextScheduledOrder).autoConsist;
}
}

TrainMotion

Full name: jfreerails.world.train.TrainMotion

Documentation

/**
* <p>
* This immutable class provides methods that return a train's position and
* speed at any time within an interval. An instance of this class will be
* stored on the world object for each train rather the train's position. The
* reasons for this are as follows.
*
* <ol type="i">
* <li> It decouples the number of game updates per second and number of frames
* per second shown by the client. If the train's position were stored on the
* world object, it would get updated each game tick. But this would mean that
* if the game was being updated 10 times per second, even if the client was
* displaying 50 FPS, the train's motion would still appear jerky since its
* position would only change 10 times per second. </li>
* <li>
*
* It makes supporting low bandwidth networks easier since it allows the server
* to send updates less frequently. </li>
* </p>
*
*
* @author Luke
* @see jfreerails.world.train.PathOnTiles
* @see jfreerails.world.train.CompositeSpeedAgainstTime
*/

Source Code

/**
* <p>
* This immutable class provides methods that return a train's position and
* speed at any time within an interval. An instance of this class will be
* stored on the world object for each train rather the train's position. The
* reasons for this are as follows.
*
* <ol type="i">
* <li> It decouples the number of game updates per second and number of frames
* per second shown by the client. If the train's position were stored on the
* world object, it would get updated each game tick. But this would mean that
* if the game was being updated 10 times per second, even if the client was
* displaying 50 FPS, the train's motion would still appear jerky since its
* position would only change 10 times per second. </li>
* <li>
*
* It makes supporting low bandwidth networks easier since it allows the server
* to send updates less frequently. </li>
* </p>
*
*
* @author Luke
* @see jfreerails.world.train.PathOnTiles
* @see jfreerails.world.train.CompositeSpeedAgainstTime
*/
strictfp public class TrainMotion implements Activity<TrainPositionOnMap> {
private static final long serialVersionUID = 3618423722025891641L;
private final double duration, distanceEngineWillTravel;
private final double initialPosition;
private final PathOnTiles path;
private final SpeedAgainstTime speeds;
private final int trainLength;
private final SpeedTimeAndStatus.TrainActivity activity;
/**
* Creates a new TrainMotion instance.
*
* @param path
* the path the train will take.
* @param engineStep
* the position measured in tiles that trains engine is along the
* path
* @param trainLength
* the length of the train, as returned by
* <code>TrainModel.getLength()</code>.
* @throws IllegalArgumentException
* if trainLength is out the range
* <code>trainLength &gt; TrainModel.WAGON_LENGTH || trainLength &lt; TrainModel.MAX_TRAIN_LENGTH</code>
* @throws IllegalArgumentException
* if
* <code>path.getDistance(engineStep) &lt; trainLength</code>.
* @throws IllegalArgumentException
* if
* <code>(path.getLength() - initialPosition) &gt; speeds.getTotalDistance()</code>.
*/
public TrainMotion(PathOnTiles path, int engineStep, int trainLength,
SpeedAgainstTime speeds) {
if (trainLength < TrainModel.WAGON_LENGTH
|| trainLength > TrainModel.MAX_TRAIN_LENGTH)
throw new IllegalArgumentException();
this.path = path;
this.speeds = speeds;
this.trainLength = trainLength;
if(engineStep > path.steps())
throw new ArrayIndexOutOfBoundsException(String.valueOf(engineStep));
initialPosition = path.getDistance(engineStep);
if (initialPosition < trainLength)
throw new IllegalArgumentException(
"The engine's initial position is not far enough along the path for "
+ "the train's initial position to be specified.");
double totalPathDistance = path.getTotalDistance();
distanceEngineWillTravel = totalPathDistance - initialPosition;
if (distanceEngineWillTravel > speeds.getS())
throw new IllegalArgumentException(
"The train's speed is not defined for the whole of the journey.");
if(distanceEngineWillTravel == 0){
duration = 0d;
}else{
double tempDuration = speeds.calcT(distanceEngineWillTravel);
while((speeds.calcS(tempDuration) - distanceEngineWillTravel) > 0){
tempDuration -= Math.ulp(tempDuration);
}
duration = tempDuration;
}
activity = SpeedTimeAndStatus.TrainActivity.READY;
sanityCheck();
}
/** Checks we are not creating an object with an inconsistent state. That is, at the
* time stored in the field duration, the engine must not have gone off the end of the path.*/
private void sanityCheck() {
double offset = calcOffSet(duration);
double totalLength = path.getTotalDistance();
double trainLengthDouble = trainLength;
if(totalLength < offset + trainLengthDouble)
throw new IllegalStateException(offset +" + "+ trainLengthDouble+" > " +totalLength);
}
public TrainMotion(PathOnTiles path, int trainLength, double duration, SpeedTimeAndStatus.TrainActivity act){
this.path = path;
this.trainLength = trainLength;
this.activity = act;
this.distanceEngineWillTravel = 0;
this.initialPosition = path.getTotalDistance();
this.speeds = ConstAcc.STOPPED;
this.duration = duration;
}
private double calcOffSet(double t) {
double offset = getDistance(t) + initialPosition - trainLength;
return offset;
}
void checkT(double t) {
if (t < 0d || t > duration)
throw new IllegalArgumentException("t=" + t + ", but duration="
+ duration);
}
public double duration() {
return duration;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TrainMotion))
return false;
final TrainMotion trainMotion = (TrainMotion) o;
if (trainLength != trainMotion.trainLength)
return false;
if (!path.equals(trainMotion.path))
return false;
if (!speeds.equals(trainMotion.speeds))
return false;
return true;
}
/**
* Returns the train's distance along the track from the point the train was
* at at time <code>getStart()</code> at the specified time.
*
* @param t
* the time.
* @return the distance
* @throws IllegalArgumentException
* if t is outside the interval
*/
public double getDistance(double t) {
checkT(t);
t = Math.min(t, speeds.getT());
return speeds.calcS(t);
}
public PositionOnTrack getFinalPosition() {
return path.getFinalPosition();
}
public double getSpeedAtEnd() {
double finalT = speeds.getT();
return speeds.calcV(finalT);
}
/**
* Returns the train's position at the specified time.
*
* @param t
* the time.
* @return the train's position.
* @throws IllegalArgumentException
* if t is outside the interval
*/
public TrainPositionOnMap getState(double t) {
t = Math.min(t, speeds.getT());
double offset = calcOffSet(t);
FreerailsPathIterator pathIt = path.subPath(offset, trainLength);
double speed = speeds.calcV(t);
double acceleration = speeds.calcA(t);
TrainPositionOnMap tpom = TrainPositionOnMap
.createInSameDirectionAsPath(pathIt, speed, acceleration,
activity);
return tpom.reverse();
}
/**
* Returns a PathOnTiles object that identifies the tiles the train is on at
* the specified time.
*
* @param t
* the time.
* @return an array of the tiles the train is on
* @throws IllegalArgumentException
* if t is outside the interval
*/
public PathOnTiles getTiles(double t) {
checkT(t);
t = Math.min(t, speeds.getT());
double start = calcOffSet(t);
double end = start + trainLength;
ArrayList<Step> steps = new ArrayList<Step>();
double distanceSoFar = 0;
int stepsBeforeStart = 0;
int stepsAfterEnd = 0;
for (int i = 0; i < path.steps(); i++) {
if (distanceSoFar > end)
stepsAfterEnd++;
Step step = path.getStep(i);
distanceSoFar += step.getLength();
if (distanceSoFar < start)
stepsBeforeStart++;
}
if (distanceSoFar < start) {
// throw new IllegalStateException();
}
if (distanceSoFar < (end - 0.1)) {
// throw new IllegalStateException();
}
int lastStep = path.steps() - stepsAfterEnd;
for (int i = stepsBeforeStart; i < lastStep; i++) {
steps.add(path.getStep(i));
}
ImPoint p = path.getStart();
int x = p.x;
int y = p.y;
for (int i = 0; i < stepsBeforeStart; i++) {
Step step = path.getStep(i);
x += step.deltaX;
y += step.deltaY;
}
ImPoint startPoint = new ImPoint(x, y);
PathOnTiles pathOnTiles = new PathOnTiles(startPoint, steps);
return pathOnTiles;
}
public int getTrainLength() {
return trainLength;
}
@Override
public int hashCode() {
int result;
result = path.hashCode();
result = 29 * result + speeds.hashCode();
result = 29 * result + trainLength;
return result;
}
public PathOnTiles getPath() {
return path;
}
public SpeedTimeAndStatus.TrainActivity getActivity() {
return activity;
}
public double getInitialPosition() {
return initialPosition;
}
}

PathWalker

Full name: jfreerails.world.train.PathWalker

Documentation

/**
* This interface lets the caller retrieve a path broken into a series of steps,
* whose length the caller specifies. E.g. it could be used to get the sub
* section of a path that a train travels during an given time interval.
*
* @author Luke
*/

Source Code

/**
* This interface lets the caller retrieve a path broken into a series of steps,
* whose length the caller specifies. E.g. it could be used to get the sub
* section of a path that a train travels during an given time interval.
*
* @author Luke
*/
public interface PathWalker extends FreerailsPathIterator,
FreerailsMutableSerializable {
/**
* Returns true if we have not reached the end of the path.
*/
boolean canStepForward();
/**
* Moves this path walker forward by the specified distance along the path
* and returns a path iterator to retrieve the section of the path travelled
* during this move.
*/
void stepForward(double distance);
}

TrackSectionTest

Full name: jfreerails.world.track.TrackSectionTest

Documentation

/**
* Test class for verifying the equality logic of the TrackSection class.
* This test ensures that the equals method correctly identifies when two TrackSection
* instances are considered equal based on their properties.
*
* @author John Doe
* @since 1.0
* @see TrackSection
* @see TestCase
*/

Source Code

public class TrackSectionTest extends TestCase {
public void testEqualsObject() {
TrackSection a = new TrackSection(Step.EAST, new ImPoint(10, 5));
TrackSection b = new TrackSection(Step.WEST, new ImPoint(11, 5));
assertEquals(a, a);
assertEquals(b, b);
assertEquals(a, b);
assertEquals(b, a);
}
}

TrackConfigurationTest

Full name: jfreerails.world.track.TrackConfigurationTest

Documentation

/**
* JUnit test.
*
* @author lindsal
*/

Source Code

/**
* JUnit test.
*
* @author lindsal
*/
public class TrackConfigurationTest extends TestCase {
public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}
public static Test suite() {
TestSuite suite = new TestSuite(TrackConfigurationTest.class);
return suite;
}
public TrackConfigurationTest(java.lang.String testName) {
super(testName);
}
public void testAdd() {
TrackConfiguration a = TrackConfiguration.getFlatInstance("000010000");
TrackConfiguration b = TrackConfiguration.add(a, Step.NORTH_WEST);
assertEquals(TrackConfiguration.getFlatInstance("100010000"), b);
assertEquals(false, a == b);
}
public void testGet8And9bitTemplate() {
for (int i = 0; i < 512; i++) {
TrackConfiguration tc = TrackConfiguration.from9bitTemplate(i);
assertEquals(i, tc.get9bitTemplate());
}
for (Step v : Step.getList()) {
TrackConfiguration tc = TrackConfiguration.getFlatInstance(v);
assertEquals(v.get9bitTemplate(), tc.get9bitTemplate());
assertEquals(v.get8bitTemplate(), tc.get8bitTemplate());
TrackConfiguration tc2 = TrackConfiguration.from9bitTemplate(v
.get9bitTemplate());
assertEquals(tc, tc2);
}
}
public void testGetLength() {
TrackConfiguration a = TrackConfiguration.getFlatInstance("010010000");
TrackConfiguration b = TrackConfiguration.getFlatInstance("010010010");
assertEquals(30, a.getLength());
assertEquals(60, b.getLength());
}
public void testSubtract() {
TrackConfiguration a = TrackConfiguration.getFlatInstance("100010000");
TrackConfiguration b = TrackConfiguration.subtract(a, Step.NORTH_WEST);
assertEquals(TrackConfiguration.getFlatInstance("000010000"), b);
}
public void testToString() {
TrackConfiguration a = TrackConfiguration.getFlatInstance("100010000");
assertEquals("tile center, north west", a.toString());
a = TrackConfiguration.getFlatInstance(Step.NORTH_WEST);
assertEquals("no tile center, north west", a.toString());
a = TrackConfiguration.getFlatInstance("000010000");
assertEquals("tile center", a.toString());
a = TrackConfiguration.getFlatInstance("000000000");
assertEquals("no tile center", a.toString());
// Check that no two track configurations have the same String
// representation.
HashSet<String> strings = new HashSet<String>();
for (int i = 0; i < 512; i++) {
TrackConfiguration test = TrackConfiguration.from9bitTemplate(i);
String toString = test.toString();
if (strings.contains(toString)) {
fail(toString + " " + i);
}
strings.add(toString);
}
}
}

TrackPieceImplTest

Full name: jfreerails.world.track.TrackPieceImplTest

Documentation

/**
* Test class for the TrackPieceImpl class, focusing on the equals method.
* This test verifies the correctness of the equals method by comparing instances
* with different configurations, rules, and cloned objects.
*
* @see TrackConfiguration
* @see TrackRule
* @see World
* @see Utils
*/

Source Code

public class TrackPieceImplTest extends TestCase {
private World w;
@Override
protected void setUp() throws Exception {
w = MapFixtureFactory2.getCopy();
}
public void testEqualsObject() {
TrackConfiguration tc1 = TrackConfiguration.getFlatInstance(Step.NORTH);
TrackRule rule0 = (TrackRule) w.get(SKEY.TRACK_RULES, 0);
TrackRule rule4 = (TrackRule) w.get(SKEY.TRACK_RULES, 4);
TrackPieceImpl tp1 = new TrackPieceImpl(tc1, rule0, 0, 0);
assertEquals(tp1, tp1);
TrackPieceImpl tp2 = new TrackPieceImpl(tc1, rule4, 0, 4);
assertFalse(tp1.equals(tp2));
TrackPieceImpl tp1Clone = (TrackPieceImpl) Utils
.cloneBySerialisation(tp1);
assertEquals(tp1, tp1Clone);
}
}

LegalTrackConfigurationsTest

Full name: jfreerails.world.track.LegalTrackConfigurationsTest

Documentation

/**
* JUnit test.
*
* @author lindsal
*/

Source Code

/**
* JUnit test.
*
* @author lindsal
*/
public class LegalTrackConfigurationsTest extends TestCase {
public LegalTrackConfigurationsTest(java.lang.String testName) {
super(testName);
}
public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}
public static Test suite() {
return new TestSuite(LegalTrackConfigurationsTest.class);
}
public void testTrackPieceIsLegal() {
ArrayList<String> templates = new ArrayList<String>();
templates.add("000111000");
LegalTrackConfigurations ltc = new LegalTrackConfigurations(-1,
templates);
TrackConfiguration template = TrackConfiguration
.getFlatInstance("010010010");
assertEquals(true, ltc.trackConfigurationIsLegal(template));
template = TrackConfiguration.getFlatInstance("010111000");
assertEquals(false, ltc.trackConfigurationIsLegal(template));
}
}

CompositeSpeedAgainstTimeTest

Full name: jfreerails.world.train.CompositeSpeedAgainstTimeTest

Documentation

/**
* Test class for the CompositeSpeedAgainstTime class, verifying its correctness
* and adherence to expected contracts. This class contains test cases to validate
* boundary conditions, calculation accuracy, and contract compliance for composite
* speed-time relationships.
*
* @see CompositeSpeedAgainstTime
* @see SpeedAgainstTime
* @see ConstAccTest
*/

Source Code

public class CompositeSpeedAgainstTimeTest extends TestCase {
public void testBounds(){
SpeedAgainstTime sat = ConstAcc.uas(10, 2, 400d);
CompositeSpeedAgainstTime csat = new CompositeSpeedAgainstTime(sat);
double t = csat.duration();
double t2 = csat.calcT(400d);
assertEquals(t, t2);
double s = csat.calcS(t);
assertEquals(400d, s);
double t3 = csat.calcT(0d);
assertEquals(0d, t3);
}
public void testContract(){
Random r = new Random(123);
for(int i = 0 ; i < 1000; i++){
int numberOfParts = r.nextInt(10) + 1;
SpeedAgainstTime[] parts = new SpeedAgainstTime[numberOfParts];
for(int j = 0; j < numberOfParts; j++){
parts[j] = ConstAcc.uat(r.nextDouble(), r.nextDouble(), r.nextDouble());
}
CompositeSpeedAgainstTime csat = new CompositeSpeedAgainstTime(parts);
ConstAccTest.checkContract(csat);
}
}
}

MutableScheduleTest

Full name: jfreerails.world.train.MutableScheduleTest

Documentation

/**
* Test class for the MutableSchedule class, verifying its behavior when adding TrainOrdersModel instances
* and retrieving the station to go to. This test ensures the correctness of the getStationToGoto method
* after order additions.
*
* @author John Doe
* @see TrainOrdersModel
* @see MutableSchedule
*/

Source Code

public class MutableScheduleTest extends TestCase {
public void test1() {
TrainOrdersModel order0 = new TrainOrdersModel(0, null, false, false);
TrainOrdersModel order1 = new TrainOrdersModel(1, null, false, false);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
int station2Goto = s.getStationToGoto();
assertEquals(0, station2Goto);
// ImmutableSchedule is = s.toImmutableSchedule();
//
// int i = is.getStationToGoto();
}
}

Methods

ConstAccTest

Full name: jfreerails.world.train.ConstAccTest

Documentation

/**
* Test class for the ConstAcc class, verifying method equivalences, equality checks,
* and contract compliance for the SpeedAgainstTime interface.
*
* This class contains multiple test cases to ensure the correctness of the
* ConstAcc implementation, including comparisons between different constructor methods,
* equality validation, and validation of the interface contract through edge cases
* and precision checks.
*
* @author John Doe
* @since 1.0
* @see ConstAcc
* @see SpeedAgainstTime
* @see TestCase
*/

Source Code

public class ConstAccTest extends TestCase {
public void testTandS() {
SpeedAgainstTime acc1 = ConstAcc.uat(0, 10, 5);
double s = acc1.getS();
SpeedAgainstTime acc2 = ConstAcc.uas(0, 10, s);
assertEquals(acc1, acc2);
acc1 = ConstAcc.uat(10, 0, 5);
assertEquals(50, acc1.getS(), 0.00001);
acc2 = ConstAcc.uas(10, 0, acc1.getS());
assertEquals(acc1, acc2);
}
public void testEquals() {
SpeedAgainstTime acc1 = ConstAcc.uat(0, 10, 4);
SpeedAgainstTime acc2 = ConstAcc.uat(0, 10, 4);
assertEquals(acc1, acc2);
}
public void testContract(){
Random r = new Random(88);
for(int i = 0; i < 1000; i++){
ConstAcc acc1 = ConstAcc.uat(r.nextDouble(), r.nextDouble(), r.nextDouble());
checkContract(acc1);
ConstAcc acc2 = ConstAcc.uas(r.nextDouble(), r.nextDouble(), r.nextDouble());
checkContract(acc2);
}
}
/** Checks the specified object satisfies the contract defined by
* the interface SpeedAgainstTime.
*/
public static void checkContract(SpeedAgainstTime sat){
double s = sat.getS();
double ulps = Math.ulp(s);
double t = sat.getT();
double ulpt = Math.ulp(t);
//Check calcS()
checkCalcSCalcVandCalcA(sat, 0 - Double.MIN_VALUE);
checkCalcSCalcVandCalcA(sat, t + ulpt);
checkCalcSCalcVandCalcA(sat, 0 + Double.MIN_VALUE);
checkCalcSCalcVandCalcA(sat, t - ulpt);
for(double d = 0; d < 1d; d += 0.1d){
checkCalcSCalcVandCalcA(sat, t * d);
}
double actualS = sat.calcS(0);
assertEquals(0d, actualS);
actualS = sat.calcS(t);
assertEquals(s, actualS);
//Check calcT()
checkCalcT(sat, 0 - Double.MIN_VALUE);
checkCalcT(sat, s + ulps);
checkCalcT(sat, 0 + Double.MIN_VALUE);
checkCalcT(sat, s - ulps);
for(double d = 0; d < 1d; d += 0.1d){
checkCalcT(sat, s * d);
}
double actualT = sat.calcT(0);
assertEquals(0d, actualT);
actualT = sat.calcT(s);
assertEquals(t, actualT);
}
private static void checkCalcSCalcVandCalcA(SpeedAgainstTime sat, double t){
boolean exceptionExpected = (t < 0) || ( t > sat.getT());
try{
double actualS = sat.calcS(t);
assertTrue(actualS >= 0);
assertTrue(actualS <= sat.getS());
assertFalse(exceptionExpected);
}catch (IllegalArgumentException e) {
assertTrue(exceptionExpected);
}
//Also check getV and getA
try{
double v = sat.calcV(t);
assertTrue(v >= 0);
assertFalse(exceptionExpected);
}catch (IllegalArgumentException e) {
assertTrue(exceptionExpected);
}
try{
sat.calcA(t);
assertFalse(exceptionExpected);
}catch (IllegalArgumentException e) {
assertTrue(exceptionExpected);
}
}
private static void checkCalcT(SpeedAgainstTime sat, double s){
boolean exceptionExpected = (s < 0) || ( s > sat.getS());
try{
double actualT = sat.calcT(s);
assertTrue(actualT >= 0);
assertTrue(actualT <= sat.getT());
assertFalse(exceptionExpected);
}catch (IllegalArgumentException e) {
assertTrue(exceptionExpected);
}
}
}

SimplePathIteratorImplTest

Full name: jfreerails.world.train.SimplePathIteratorImplTest

Documentation

/**
* Junit test.
*
* @author Luke
*/

Source Code

/**
* Junit test.
*
* @author Luke
*/
public class SimplePathIteratorImplTest extends TestCase {
public SimplePathIteratorImplTest(String arg0) {
super(arg0);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(SimplePathIteratorImplTest.class);
}
public void testHasNext() {
int[] xpoints = { 0, 100 };
int[] ypoints = { 0, 0 };
FreerailsPathIterator it = new SimplePathIteratorImpl(xpoints, ypoints);
assertTrue(it.hasNext());
it.nextSegment(new IntLine(0, 0, 0, 0));
assertTrue(!it.hasNext());
}
public void testNextSegment() {
int[] xpoints = { 1, 2, 3 };
int[] ypoints = { 4, 5, 6 };
FreerailsPathIterator it = new SimplePathIteratorImpl(xpoints, ypoints);
assertTrue(it.hasNext());
IntLine line = new IntLine(0, 0, 0, 0);
it.nextSegment(line);
assertLineEquals(1, 4, 2, 5, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(2, 5, 3, 6, line);
assertTrue(!it.hasNext());
}
private void assertLineEquals(int x1, int y1, int x2, int y2, IntLine line) {
assertEquals(x1, line.x1);
assertEquals(x2, line.x2);
assertEquals(y1, line.y1);
assertEquals(y2, line.y2);
}
}

TrainPositionOnMapTest

Full name: jfreerails.world.train.TrainPositionOnMapTest

Documentation

/**
* Junit test.
*
* @author Luke Lindsay 26-Oct-2002
*
*/

Source Code

/**
* Junit test.
*
* @author Luke Lindsay 26-Oct-2002
*
*/
public class TrainPositionOnMapTest extends TestCase {
public TrainPositionOnMapTest(String arg0) {
super(arg0);
}
public void testGetLength() {
TrainPositionOnMap a;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20, 30, 40 },
new int[] { 11, 22, 33, 44 });
assertEquals(4, a.getLength());
}
public void testGetPoint() {
TrainPositionOnMap a;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
assertEquals(a.getX(0), 10);
assertEquals(a.getY(0), 11);
assertEquals(a.getX(1), 20);
assertEquals(a.getY(1), 22);
}
public void testPath() {
TrainPositionOnMap a;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20, 30, 40 },
new int[] { 11, 22, 33, 44 });
FreerailsPathIterator path = a.path();
IntLine line = new IntLine();
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(10, 11, 20, 22));
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(20, 22, 30, 33));
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(30, 33, 40, 44));
assertTrue(!path.hasNext());
}
public void testReversePath() {
TrainPositionOnMap a;
a = TrainPositionOnMap.createInstance(new int[] { 40, 30, 20, 10 },
new int[] { 44, 33, 22, 11 });
FreerailsPathIterator path = a.reversePath();
IntLine line = new IntLine();
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(10, 11, 20, 22));
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(20, 22, 30, 33));
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(30, 33, 40, 44));
assertTrue(!path.hasNext());
}
/*
* Test for TrainPosition createInstance(int[], int[])
*/
public void testCreateInstanceIArrayIArray() {
try {
TrainPositionOnMap.createInstance(new int[] { 40, 30, 20, 10 },
new int[] { 44, 33, 22, 11 });
} catch (Exception e) {
assertTrue(false);
}
try {
TrainPositionOnMap.createInstance(new int[] { 40, 30, 20 },
new int[] { 44, 33, 22, 11 });
assertTrue(false);
} catch (Exception e) {
}
}
/*
* public void testAdd() { TrainPosition a, b, c, d, e, f, g, h , i, j;
* a=TrainPosition.createInstance(new int[] {10,20}, new int[]{11,22});
* b=TrainPosition.createInstance(new int[] {20, 30}, new int[]{22,33});
* c=TrainPosition.createInstance(new int[] {10, 30}, new int[]{11, 33});
*
* d=TrainPosition.add(a, b); assertEquals(d, c); e=TrainPosition.add(b, a);
* assertEquals(e, c);
*
*
* f = TrainPosition.createInstance( new int[] { 40, 50 }, new int[] { 44,
* 55 }); g = TrainPosition.createInstance( new int[] { 10, 30, 40 }, new
* int[] { 11, 33, 44 });
*
* i = TrainPosition.createInstance( new int[] { 10, 30, 50 }, new int[] {
* 11, 33, 55 }); j = TrainPosition.add(f, g); assertEquals(i, j);
*
*
* }
*/
/*
* public void testRemove() { TrainPosition a, b, c, d, e, f, g, h , i, j ,
* k; a=TrainPosition.createInstance(new int[] {10,20 ,40 , 50, 60}, new
* int[]{11,22, 44, 55 , 66}); b=TrainPosition.createInstance(new int[] {10,
* 20, 30}, new int[]{11,22,33}); c=TrainPosition.createInstance(new int[]
* {48, 50, 60}, new int[]{49,55, 66});
*
* d=TrainPosition.createInstance(new int[] {30, 40 , 50, 60}, new int[]{33,
* 44, 55, 66}); e=TrainPosition.createInstance(new int[] {10, 20, 40, 48},
* new int[]{11, 22, 44, 49});
*
* f=TrainPosition.remove(a, b); assertEquals(f, d);
*
* g=TrainPosition.remove(a, c); assertEquals(g, e);
*
* h = TrainPosition.createInstance( new int[] { 10, 30, 50 }, new int[] {
* 11, 33, 55 });
*
* i = TrainPosition.createInstance( new int[] { 10, 20 }, new int[] { 11,
* 22 });
*
* j = TrainPosition.createInstance( new int[] { 20, 30, 50 }, new int[] {
* 22, 33, 55 });
*
* k = TrainPosition.remove(h, i);
*
* assertEquals(k, j); }
*
*/
/*
* public void testCanBeAdded() { TrainPosition a, b, c, d;
* a=TrainPosition.createInstance(new int[] {10,20}, new int[]{11,22});
* b=TrainPosition.createInstance(new int[] {20, 30}, new int[]{22,33});
* c=TrainPosition.createInstance(new int[] {30, 40}, new int[]{33,44});
*
* assertTrue(TrainPosition.canBeAdded(a, b));
* assertTrue(TrainPosition.canBeAdded(b, a));
* assertTrue(TrainPosition.canBeAdded(b, c));
* assertTrue(!TrainPosition.canBeAdded(c, b));
*
* assertTrue(!TrainPosition.canBeAdded(a, c));
* assertTrue(!TrainPosition.canBeAdded(c, a));
*
* //Test that we cannot add a position to itself
* assertTrue(!TrainPosition.canBeAdded(a, a));
* assertTrue(!TrainPosition.canBeAdded(b, b));
* assertTrue(!TrainPosition.canBeAdded(c, c)); }
*/
/*
* public void testCanBeRemoved() { TrainPosition a, b, c, d;
* a=TrainPosition.createInstance(new int[] {10,20 ,40 , 50}, new
* int[]{11,22, 44, 55}); b=TrainPosition.createInstance(new int[] {10, 20,
* 30}, new int[]{11,22,33}); c=TrainPosition.createInstance(new int[] {30,
* 40, 50}, new int[]{33,44,55});
*
* assertTrue(TrainPosition.canBeRemoved(a, b));
*
* assertTrue(!TrainPosition.canBeRemoved(b, a));
*
* assertTrue(TrainPosition.canBeRemoved(a, c));
*
* assertTrue(!TrainPosition.canBeRemoved(c, a));
*
* //Test that we cannot remove a position from itself
* assertTrue(!TrainPosition.canBeRemoved(a, a));
* assertTrue(!TrainPosition.canBeRemoved(b, b));
* assertTrue(!TrainPosition.canBeRemoved(c, c)); }
*/
public void testAddToHead() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
TrainPositionOnMap d;
TrainPositionOnMap f;
TrainPositionOnMap g;
TrainPositionOnMap i;
TrainPositionOnMap j;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
b = TrainPositionOnMap.createInstance(new int[] { 20, 30 }, new int[] {
22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 10, 30 }, new int[] {
11, 33 });
d = b.addToHead(a);
assertEquals(d, c);
f = TrainPositionOnMap.createInstance(new int[] { 40, 50 }, new int[] {
44, 55 });
g = TrainPositionOnMap.createInstance(new int[] { 10, 30, 40 },
new int[] { 11, 33, 44 });
i = TrainPositionOnMap.createInstance(new int[] { 10, 30, 50 },
new int[] { 11, 33, 55 });
j = f.addToHead(g);
assertEquals(i, j);
}
public void testCanAddToHead() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
b = TrainPositionOnMap.createInstance(new int[] { 20, 30 }, new int[] {
22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 30, 40 }, new int[] {
33, 44 });
assertTrue(b.canAddToHead(a));
assertTrue(!a.canAddToHead(b));
assertTrue(c.canAddToHead(b));
assertTrue(!b.canAddToHead(c));
assertTrue(!c.canAddToHead(a));
assertTrue(!a.canAddToHead(c));
}
public void testAddToTail() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
TrainPositionOnMap d;
TrainPositionOnMap f;
TrainPositionOnMap g;
TrainPositionOnMap i;
TrainPositionOnMap j;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
b = TrainPositionOnMap.createInstance(new int[] { 20, 30 }, new int[] {
22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 10, 30 }, new int[] {
11, 33 });
d = a.addToTail(b);
assertEquals(d, c);
f = TrainPositionOnMap.createInstance(new int[] { 40, 50 }, new int[] {
44, 55 });
g = TrainPositionOnMap.createInstance(new int[] { 10, 30, 40 },
new int[] { 11, 33, 44 });
i = TrainPositionOnMap.createInstance(new int[] { 10, 30, 50 },
new int[] { 11, 33, 55 });
j = g.addToTail(f);
assertEquals(i, j);
}
public void testCanAddToTail() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
b = TrainPositionOnMap.createInstance(new int[] { 20, 30 }, new int[] {
22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 30, 40 }, new int[] {
33, 44 });
assertTrue(!b.canAddToTail(a));
assertTrue(a.canAddToTail(b));
assertTrue(!c.canAddToTail(b));
assertTrue(b.canAddToTail(c));
assertTrue(!c.canAddToTail(a));
assertTrue(!a.canAddToTail(c));
}
public void testCanRemoveFromHead() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20, 40, 50 },
new int[] { 11, 22, 44, 55 });
b = TrainPositionOnMap.createInstance(new int[] { 10, 20, 30 },
new int[] { 11, 22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 30, 40, 50 },
new int[] { 33, 44, 55 });
assertTrue(!b.canRemoveFromHead(a));
assertTrue(a.canRemoveFromHead(b));
assertTrue(!c.canRemoveFromHead(b));
assertTrue(!b.canRemoveFromHead(c));
assertTrue(!c.canRemoveFromHead(a));
assertTrue(!a.canRemoveFromHead(c));
}
public void testRemoveFromTail() {
TrainPositionOnMap a;
TrainPositionOnMap c;
TrainPositionOnMap e;
TrainPositionOnMap f;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20, 40, 50, 60 },
new int[] { 11, 22, 44, 55, 66 });
c = TrainPositionOnMap.createInstance(new int[] { 48, 50, 60 },
new int[] { 49, 55, 66 });
e = TrainPositionOnMap.createInstance(new int[] { 10, 20, 40, 48 },
new int[] { 11, 22, 44, 49 });
f = a.removeFromTail(c);
assertEquals(e, f);
}
public void testCanRemoveFromTail() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20, 40, 50 },
new int[] { 11, 22, 44, 55 });
b = TrainPositionOnMap.createInstance(new int[] { 10, 20, 30 },
new int[] { 11, 22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 30, 40, 50 },
new int[] { 33, 44, 55 });
assertTrue(!b.canRemoveFromTail(a));
assertTrue(!a.canRemoveFromTail(b));
assertTrue(!c.canRemoveFromTail(b));
assertTrue(!b.canRemoveFromTail(c));
assertTrue(!c.canRemoveFromTail(a));
assertTrue(a.canRemoveFromTail(c));
}
public void testEquals() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
b = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
c = TrainPositionOnMap.createInstance(new int[] { 30, 40 }, new int[] {
33, 44 });
assertTrue(!a.equals(null));
assertTrue(!a.equals(new Object()));
assertTrue(a.equals(a));
assertTrue(a.equals(b));
assertTrue(!a.equals(c));
}
/*
* Test for TrainPosition createInstance(FreerailsPathIterator)
*/
public void testCreateInstanceFreerailsPathIterator() {
FreerailsPathIterator path = new SimplePathIteratorImpl(new int[] { 40,
30, 20, 10 }, new int[] { 44, 33, 22, 11 });
TrainPositionOnMap a = TrainPositionOnMap
.createInSameDirectionAsPath(path);
assertEquals(a.getLength(), 4);
assertEquals(a.getX(0), 40);
assertEquals(a.getY(0), 44);
assertEquals(a.getX(1), 30);
assertEquals(a.getY(1), 33);
assertEquals(a.getX(2), 20);
assertEquals(a.getY(2), 22);
assertEquals(a.getX(3), 10);
assertEquals(a.getY(3), 11);
}
public void testCreateInOppositeDirectionToPath() {
FreerailsPathIterator path = new SimplePathIteratorImpl(new int[] { 40,
30, 20, 10 }, new int[] { 44, 33, 22, 11 });
TrainPositionOnMap a = TrainPositionOnMap.createInSameDirectionAsPath(
path).reverse();
assertEquals(a.getLength(), 4);
assertEquals(a.getX(3), 40);
assertEquals(a.getY(3), 44);
assertEquals(a.getX(2), 30);
assertEquals(a.getY(2), 33);
assertEquals(a.getX(1), 20);
assertEquals(a.getY(1), 22);
assertEquals(a.getX(0), 10);
assertEquals(a.getY(0), 11);
}
}

PathWalkerImplTest

Full name: jfreerails.world.train.PathWalkerImplTest

Documentation

/**
* JUnit test.
*
* @author Luke
*/

Source Code

/**
* JUnit test.
*
* @author Luke
*/
public class PathWalkerImplTest extends TestCase {
FreerailsPathIterator it;
PathWalker pw;
public PathWalkerImplTest(String arg0) {
super(arg0);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(PathWalkerImplTest.class);
}
/*
* Test for boolean canStepForward()
*/
public void testCanStepForward() {
setup();
assertTrue(pw.canStepForward());
pw.stepForward(500); // The path length is 200;
moveToNextLimit();
assertTrue(!pw.canStepForward());
setup();
assertTrue(pw.canStepForward());
pw.stepForward(10);
assertTrue(pw.canStepForward());
IntLine line = new IntLine();
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertLineEquals(0, 0, 10, 0, line);
assertTrue(!pw.hasNext());
assertTrue(pw.canStepForward());
pw.stepForward(500); // The path length is 200;
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertLineEquals(10, 0, 100, 0, line);
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertLineEquals(100, 0, 100, 100, line);
assertTrue(!pw.canStepForward());
}
private void moveToNextLimit() {
IntLine line = new IntLine();
while (pw.hasNext()) {
pw.nextSegment(line);
}
}
public void testHasNext() {
IntLine line = new IntLine();
setup();
assertTrue(!pw.hasNext());
pw.stepForward(10);
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertLineEquals(0, 0, 10, 0, line);
assertTrue(!pw.hasNext());
setup();
assertTrue(!pw.hasNext());
pw.stepForward(110);
assertTrue(pw.hasNext());
line = new IntLine();
pw.nextSegment(line);
assertLineEquals(0, 0, 100, 0, line);
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertLineEquals(100, 0, 100, 10, line);
assertTrue(!pw.hasNext());
/*
* Now test with underlying pathIterators with few elements.
*/
ArrayList<Point> points = new ArrayList<Point>();
assertHasNextEqualsFalse(points);
points = new ArrayList<Point>();
points.add(new Point(0, 0));
assertHasNextEqualsFalse(points);
points = new ArrayList<Point>();
points.add(new Point(0, 0));
points.add(new Point(100, 0));
FreerailsPathIterator it2 = FreerailsPathIteratorImpl
.forwardsIterator(points);
assertTrue(it2.hasNext());
pw = new PathWalkerImpl(it2);
assertTrue(!pw.hasNext());
pw.stepForward(1000);
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertTrue(!pw.hasNext());
}
void assertHasNextEqualsFalse(ArrayList<Point> points) {
FreerailsPathIterator it2 = FreerailsPathIteratorImpl
.forwardsIterator(points);
assertTrue(!it2.hasNext());
pw = new PathWalkerImpl(it2);
pw.stepForward(100);
assertTrue(!pw.hasNext());
}
public void setup() {
int[] xpoints = { 0, 100, 100 };
int[] ypoints = { 0, 0, 100 };
it = new SimplePathIteratorImpl(xpoints, ypoints);
pw = new PathWalkerImpl(it);
}
private void assertLineEquals(int x1, int y1, int x2, int y2, IntLine line) {
assertEquals(x1, line.x1);
assertEquals(x2, line.x2);
assertEquals(y1, line.y1);
assertEquals(y2, line.y2);
}
}

TrainMotionTest

Full name: jfreerails.world.train.TrainMotionTest

Documentation

/**
* Test class for verifying the correctness of the TrainMotion class's motion calculations.
* This test focuses on validating the total distance, duration, initial position, and state
* handling of a train's motion under specific acceleration scenarios. The test data is derived
* from debugger outputs to ensure accuracy.
*
* @see TrainMotion
* @see CompositeSpeedAgainstTime
*
* @since 1.0
*/

Source Code

public class TrainMotionTest extends TestCase {
/*
this= TrainMotion (id=49)
activity= SpeedTimeAndStatus$TrainActivity (id=107)
name= "READY"
ordinal= 1
distanceEngineWillTravel= 30.0
duration= 3.9936298481613424
initialPosition= 42.42640687119285
path= PathOnTiles (id=48)
start= ImPoint (id=73)
x= 14
y= 5
vectors= ImList<E> (id=75)
elementData= FreerailsSerializable[2] (id=77)
[0]= Step (id=79)
deltaX= 1
deltaY= 1
flatTrackTemplate= 256
length= 42.42640687119285
[1]= Step (id=82)
deltaX= 1
deltaY= 0
flatTrackTemplate= 32
length= 30.0
speeds= CompositeSpeedAgainstTime (id=111)
duration= 10.972888751347389
totalDistance= 97.57359312880715
values= ImList<E> (id=114)
elementData= FreerailsSerializable[2] (id=118)
[0]= ConstAcc (id=119)
a= 0.5
dt= 6.972888751347389
u= 6.5135556243263055
[1]= ConstAcc (id=121)
a= 0.0
dt= 4.0
u= 10.0
trainLength= 24
t= 3.9936298481613424
offset= 48.42640687119287
length= 24.0
72.42640687119285
*/
public void test4Bug1266695(){
//The figures are copied from the debugger.
ImPoint start = new ImPoint(14, 5);
Step[] vectors= {Step.getInstance(1,1), Step.getInstance(1,0)};
PathOnTiles path = new PathOnTiles(start, vectors);
ConstAcc constAcc0 = ConstAcc.uat(6.5135556243263055d, 0.5d, 6.972888751347389d);
ConstAcc constAcc1 = ConstAcc.uat(10.0, 0.0d, 4.0d);
SpeedAgainstTime speeds = new CompositeSpeedAgainstTime(constAcc0, constAcc1);
double expectedTotalDistance= 97.57359312880715d; //Copied from debugger.
double actualTotalDistance = speeds.getS();
assertEquals(expectedTotalDistance, actualTotalDistance,0d);
double expectedDuration = 10.972888751347389d;
double actualDuration = speeds.getT();
assertEquals(expectedDuration, actualDuration,0d);
int engineStep = 1;
int trainLength = 24;
TrainMotion motion = new TrainMotion(path,engineStep, trainLength, speeds);
double expectedInitialPosition = 42.42640687119285;
double actualInitialPosition = motion.getInitialPosition();
assertEquals(expectedInitialPosition, actualInitialPosition,0d);
//Different from above
double tooLongDuration = 3.9936298481613424d;
actualDuration = motion.duration();
assertTrue(tooLongDuration > actualDuration);
//This method used to throw an exception
@SuppressWarnings("unused") Object o = motion.getState(actualDuration);
}
}

Methods

IntLineTest

Full name: jfreerails.world.train.IntLineTest

Documentation

/**
* Junit test.
*
* @author Luke
*/

Source Code

/**
* Junit test.
*
* @author Luke
*/
public class IntLineTest extends TestCase {
public IntLineTest(String arg0) {
super(arg0);
}
public static void main(String[] args) {
junit.textui.TestRunner.run(IntLineTest.class);
}
public void testGetLength() {
IntLine line = new IntLine(0, 0, 100, 0);
assertEquals(100, line.getLength(), 0.1);
}
}

PathOnTilesTest

Full name: jfreerails.world.train.PathOnTilesTest

Documentation

/**
* JUnit test for PathOnTiles.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test for PathOnTiles.
*
* @author Luke
*
*/
public class PathOnTilesTest extends TestCase {
public void testPathOnTiles() {
ImPoint start = null;
Step[] vectors = null;
assertTrue(throwsException(start, vectors));
start = new ImPoint();
assertTrue(throwsException(start, vectors));
vectors = new Step[] { null, null };
assertTrue(throwsException(start, vectors));
vectors = new Step[] { NORTH, SOUTH };
assertFalse(throwsException(start, vectors));
}
public void testGetStepIndex() {
ImPoint start = new ImPoint();
Step[] vectors = new Step[] { SOUTH_EAST, EAST, EAST };
PathOnTiles path = new PathOnTiles(start, vectors);
assertEquals(0, path.getStepIndex(0));
assertEquals(0, path.getStepIndex(1));
assertEquals(0, path.getStepIndex(30));
assertEquals(1, path.getStepIndex(60));
assertEquals(2, path.getStepIndex(90));
}
public void testGetLength() {
ImPoint start = new ImPoint();
Step[] vectors = new Step[] { EAST, EAST, EAST };
PathOnTiles path = new PathOnTiles(start, vectors);
assertEquals(3 * Step.TILE_DIAMETER, path.getTotalDistance(), 0.001);
}
public void testGetPoint() {
ImPoint start = new ImPoint();
Step[] vectors = new Step[] { EAST, EAST, EAST };
PathOnTiles path = new PathOnTiles(start, vectors);
ImPoint expected = new ImPoint(15, 15);
ImPoint actual = path.getPoint(0);
assertEquals(expected, actual);
expected = new ImPoint(45, 15);
actual = path.getPoint(30);
assertEquals(expected, actual);
expected = new ImPoint(60, 15);
actual = path.getPoint(45);
assertEquals(expected, actual);
}
public void testSubPath() {
ImPoint start = new ImPoint();
Step[] vectors = new Step[] { EAST, EAST, EAST };
PathOnTiles path = new PathOnTiles(start, vectors);
// First check.
FreerailsPathIterator pathIt = path.subPath(0, path.getTotalDistance());
ImPoint[] expected = { new ImPoint(15, 15), new ImPoint(45, 15),
new ImPoint(75, 15), new ImPoint(105, 15) };
checkPath(pathIt, expected);
// Second check
pathIt = path.subPath(3, path.getTotalDistance() - 3);
expected = new ImPoint[] { new ImPoint(18, 15), new ImPoint(45, 15),
new ImPoint(75, 15), new ImPoint(105, 15) };
checkPath(pathIt, expected);
// 3rd check
double i = path.getTotalDistance() - 10;
pathIt = path.subPath(3, i);
expected = new ImPoint[] { new ImPoint(18, 15), new ImPoint(45, 15),
new ImPoint(75, 15), new ImPoint(98, 15) };
checkPath(pathIt, expected);
// 4th check, with a path just 1 tile long.
start = new ImPoint(5, 5);
vectors = new Step[] { SOUTH_WEST };
path = new PathOnTiles(start, vectors);
pathIt = path.subPath(18, 24);
IntLine line = new IntLine();
assertTrue(pathIt.hasNext());
pathIt.nextSegment(line);
assertEquals("The length of the train.", 24, line.getLength(), 1d);
assertFalse(pathIt.hasNext());
// 5th check, same as 2nd but with different starting position.
vectors = new Step[] { EAST, EAST, EAST };
start = new ImPoint(4, 7);
path = new PathOnTiles(start, vectors);
pathIt = path.subPath(3, path.getTotalDistance() - 3);
expected = new ImPoint[] { new ImPoint(18, 15), new ImPoint(45, 15),
new ImPoint(75, 15), new ImPoint(105, 15) };
for (int j = 0; j < expected.length; j++) {
int x = expected[j].x + start.x * TILE_DIAMETER;
int y = expected[j].y + start.y * TILE_DIAMETER;
expected[j] = new ImPoint(x, y);
}
// for (ImPoint point : expected) {
// point.x += start.x * TILE_DIAMETER;
// point.y += start.y * TILE_DIAMETER;
// }
checkPath(pathIt, expected);
}
private void checkPath(FreerailsPathIterator pathIt, ImPoint[] expected) {
IntLine line = new IntLine();
for (int i = 0; i < expected.length - 1; i++) {
assertTrue(pathIt.hasNext());
pathIt.nextSegment(line);
assertEquals(expected[i].x, line.x1);
assertEquals(expected[i + 1].x, line.x2);
assertEquals(expected[i].y, line.y1);
assertEquals(expected[i + 1].y, line.y2);
}
assertFalse(pathIt.hasNext());
}
boolean throwsException(ImPoint start, Step[] vectors) {
try {
new PathOnTiles(start, vectors);
return false;
} catch (Exception e) {
return true;
}
}
public void testTiles() {
PathOnTiles path = new PathOnTiles(new ImPoint(5, 5), SOUTH_WEST,
NORTH_EAST);
Iterator<ImPoint> it = path.tiles();
assertEquals(new ImPoint(5, 5), it.next());
assertEquals(new ImPoint(4, 6), it.next());
assertEquals(new ImPoint(5, 5), it.next());
assertFalse(it.hasNext());
}
}

PositionOnTrackTest

Full name: jfreerails.world.common.PositionOnTrackTest

Documentation

/**
* Junit test for PositionOnTrack.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* Junit test for PositionOnTrack.
*
* @author Luke Lindsay
*
*/
public class PositionOnTrackTest extends TestCase {
/**
* Constructor for PositionOnTrackTest.
*
* @param arg0
*/
public PositionOnTrackTest(String arg0) {
super(arg0);
}
public void testValidation() {
assertTrue(PositionOnTrack.MAX_COORDINATE < 70000);
assertTrue(PositionOnTrack.MAX_COORDINATE > 10000);
assertEquals(PositionOnTrack.MAX_DIRECTION, 7);
assertNoException(0, 0, Step.EAST);
assertNoException(PositionOnTrack.MAX_COORDINATE,
PositionOnTrack.MAX_COORDINATE, Step.NORTH_WEST);
assertException(-1, 0, Step.EAST);
assertException(0, -1, Step.EAST);
assertException(PositionOnTrack.MAX_COORDINATE + 1,
PositionOnTrack.MAX_COORDINATE, Step.NORTH_WEST);
assertException(PositionOnTrack.MAX_COORDINATE,
PositionOnTrack.MAX_COORDINATE + 1, Step.NORTH_WEST);
}
public void testToInt() {
PositionOnTrack p1 = PositionOnTrack.createComingFrom(10, 20,
Step.NORTH);
PositionOnTrack p2 = PositionOnTrack.createComingFrom(10, 30,
Step.NORTH);
assertTrue(p1.toInt() != p2.toInt());
}
public void testSetValuesFromInt() {
PositionOnTrack p1 = PositionOnTrack.createComingFrom(10, 20,
Step.NORTH);
int i = p1.toInt();
PositionOnTrack p2 = PositionOnTrack
.createComingFrom(60, 70, Step.EAST);
assertTrue(!p1.equals(p2));
p2.setValuesFromInt(i);
assertEquals(p1, p2);
Step v = Step.getInstance(7); // 7 is the
// maximum
// vector
// number.
p1 = PositionOnTrack.createComingFrom(PositionOnTrack.MAX_COORDINATE,
PositionOnTrack.MAX_COORDINATE, v);
i = p1.toInt();
}
/*
* Test for boolean equals(Object)
*/
public void testEqualsObject() {
PositionOnTrack p1 = PositionOnTrack.createComingFrom(10, 20,
Step.NORTH);
PositionOnTrack p2 = PositionOnTrack.createComingFrom(10, 20,
Step.NORTH);
assertEquals(p1, p2);
p1 = PositionOnTrack.createComingFrom(10, 50, Step.NORTH);
p2 = PositionOnTrack.createComingFrom(10, 20, Step.NORTH);
assertTrue(!p1.equals(p2));
}
private void assertNoException(int x, int y, Step v) {
try {
PositionOnTrack.createComingFrom(x, y, v);
} catch (Exception e) {
assertTrue(false);
}
}
private void assertException(int x, int y, Step v) {
try {
PositionOnTrack.createComingFrom(x, y, v);
assertTrue(false);
} catch (Exception e) {
}
}
public void testGetOpposite() {
PositionOnTrack p1 = PositionOnTrack.createComingFrom(10, 10,
Step.NORTH);
PositionOnTrack p2 = p1.getOpposite();
assertNotNull(p2);
PositionOnTrack p3 = PositionOnTrack.createComingFrom(10, 11,
Step.SOUTH);
assertEquals(p3, p2);
}
}

StepTest

Full name: jfreerails.world.common.StepTest

Documentation

/**
* JUnit test for OneTileMoveVector.
*
* @author Luke
*/

Source Code

/**
* JUnit test for OneTileMoveVector.
*
* @author Luke
*/
public class StepTest extends TestCase {
final Step n = Step.NORTH;
final Step ne = Step.NORTH_EAST;
final Step e = Step.EAST;
final Step se = Step.SOUTH_EAST;
final Step s = Step.SOUTH;
final Step sw = Step.SOUTH_WEST;
final Step w = Step.WEST;
final Step nw = Step.NORTH_WEST;
public StepTest(String arg0) {
super(arg0);
}
public void testGetDirection() {
double d = 0;
assertTrue(d == n.getDirection());
d = 2 * Math.PI / 8 * 1;
assertTrue(d == ne.getDirection());
}
public void testGetNearestVector() {
// Each vector should be the nearest to itself!
Step[] vectors = Step.getList();
for (int i = 0; i < vectors.length; i++) {
Step v = vectors[i];
Step v2 = Step.getNearestVector(v.deltaX, v.deltaY);
assertEquals(v, v2);
}
assertNearest(n, 0, -1);
assertNearest(n, 0, -99);
assertNearest(n, 2, -5);
assertNearest(n, -2, -5);
assertNearest(s, 2, 5);
assertNearest(w, -5, -1);
assertNearest(sw, -4, 3);
assertNearest(ne, 10, -6);
assertNearest(ne, 10, -6);
}
private void assertNearest(Step v, int dx, int dy) {
Step v2 = Step.getNearestVector(dx, dy);
assertEquals(v, v2);
}
public void testGetNewTemplateNumber() {
assertEquals(Step.NORTH.get8bitTemplate(), 1);
assertEquals(Step.NORTH_EAST.get8bitTemplate(), 2);
assertEquals(Step.EAST.get8bitTemplate(), 4);
}
}

GameCalenderTest

Full name: jfreerails.world.common.GameCalenderTest

Documentation

/**
* Junit test for GameCalendar.
*
* @author Luke
*
*/

Source Code

/**
* Junit test for GameCalendar.
*
* @author Luke
*
*/
public class GameCalenderTest extends TestCase {
public void testGetYear() {
GameCalendar gc = new GameCalendar(10, 1900);
assertEquals("1900", gc.getYearAsString(0));
assertEquals("1900", gc.getYearAsString(5));
assertEquals("1901", gc.getYearAsString(10));
assertEquals("1950", gc.getYearAsString(505));
}
public void testGetTimeOfDay() {
GameCalendar gc = new GameCalendar(24, 1900);
assertEquals("00:00", gc.getTimeOfDay(0));
assertEquals("01:00", gc.getTimeOfDay(1));
assertEquals("15:00", gc.getTimeOfDay(15));
gc = new GameCalendar(24 * 60, 1900);
assertEquals("00:00", gc.getTimeOfDay(0));
assertEquals("00:10", gc.getTimeOfDay(10));
assertEquals("05:10", gc.getTimeOfDay(310));
}
public void testGetYearAndMonth() {
GameCalendar gc = new GameCalendar(12, 1900);
assertEquals("Jan 1900", gc.getYearAndMonth(0));
assertEquals("Feb 1900", gc.getYearAndMonth(1));
assertEquals("Mar 1900", gc.getYearAndMonth(2));
assertEquals("Mar 1901", gc.getYearAndMonth(14));
}
}

ImIntsTest

Full name: jfreerails.world.common.ImIntsTest

Documentation

/**
* Test class for the ImInts class, verifying the functionality of its methods.
* This class contains test cases for the append, removeLast, and equals methods.
*
* @see ImInts
*/

Source Code

public class ImIntsTest extends TestCase {
/*
* Test method for 'jfreerails.world.common.ImInts.append(int...)'
*/
public void testAppend() {
int[] a = { 1, 2, 3 };
int[] b = { 4, 5, 6, 7 };
int[] c = { 1, 2, 3, 4, 5, 6, 7 };
ImInts ai = new ImInts(a);
ImInts ci = new ImInts(c);
assertFalse(ci.equals(ai));
assertEquals(ci, ai.append(b));
}
public void testRemoveLast(){
//Test method does not change original
ImInts original = new ImInts(1,2, 3, 4);
ImInts clone = (ImInts) Utils.cloneBySerialisation(original);
assertEquals(original, clone);
original.removeLast();
assertEquals(original, clone);
ImInts actual, expected;
actual = (new ImInts( 1, 2, 3)).removeLast();
expected = new ImInts(1,2);
assertEquals(expected, actual);
actual = (new ImInts( 1, 2)).removeLast();
expected = new ImInts(1);
assertEquals(expected, actual);
actual = (new ImInts( 1, 2, 4, 3)).removeLast();
expected = new ImInts(1, 2, 4);
assertEquals(expected, actual);
}
public void testEquals(){
int[] a = { 1, 2, 3 };
int[] b = { 1, 2, 3 };
ImInts ai = new ImInts(a);
ImInts bi = new ImInts(b);
assertEquals(ai, bi);
ImInts ci = new ImInts(1, 2, 3 );
assertEquals(ai, ci);
}
}

MiscTest

Full name: jfreerails.world.terrain.MiscTest

Documentation

/**
* Test class for verifying the correctness of hash code and equals methods
* for CityModel and TileTypeImpl classes.
*
* This class contains test cases to ensure that objects correctly implement
* the equals and hashCode methods, and that different instances are
* considered unequal.
*
* @see CityModel
* @see TileTypeImpl
* @see Utils
*/

Source Code

public class MiscTest extends TestCase {
public void testCityModel() {
CityModel cm1 = new CityModel("London", 20, 70);
CityModel cm2 = new CityModel("Cardiff", 20, 70);
testHashCodeAndEquals(cm1);
testHashCodeAndEquals(cm2);
assertDifferent(cm1, cm2);
}
public void testTileTypeImpl() {
Production[] prod = { new Production(69, 10) };
Consumption[] cons = { new Consumption(4, 4), new Consumption(4, 5) };
Conversion[] conv = { new Conversion(50, 30) };
testHashCodeAndEquals(prod[0]);
testHashCodeAndEquals(cons[0]);
testHashCodeAndEquals(conv[0]);
TileTypeImpl tt = new TileTypeImpl(0, Category.Country, "Grassland",
100, prod, cons, conv, 10);
testHashCodeAndEquals(tt);
Conversion[] conv2 = { new Conversion(5, 30) };
TileTypeImpl tt2 = new TileTypeImpl(0, Category.Country, "Grassland",
100, prod, cons, conv2, 10);
assertFalse(tt.equals(tt2));
}
private void testHashCodeAndEquals(Serializable a) {
Serializable copy = Utils.cloneBySerialisation(a);
assertEquals(a, a);
assertEquals(a, copy);
assertEquals(a.hashCode(), copy.hashCode());
}
private void assertDifferent(Object a, Object b) {
assertFalse(a.equals(b));
assertFalse(a.hashCode() == b.hashCode());
}
}

BalanceSheetGeneratorTest

Full name: jfreerails.client.view.BalanceSheetGeneratorTest

Documentation

/**
* JUnit test for BalanceSheetGenerator.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test for BalanceSheetGenerator.
*
* @author Luke
*
*/
public class BalanceSheetGeneratorTest extends TestCase {
Player player;
World world;
public void testBondsFigure() {
BalanceSheetGenerator generator = new BalanceSheetGenerator(world,
player.getPrincipal());
Money expectedBondValue = new Money(BondTransaction.BOND_VALUE_ISSUE
.getAmount());
assertEquals(expectedBondValue.changeSign(), generator.total.loans);
assertEquals(expectedBondValue.changeSign(), generator.ytd.loans);
}
public void testStockHolderEquityFigure() {
BalanceSheetGenerator generator = new BalanceSheetGenerator(world,
player.getPrincipal());
Money expectStockHolderEquity = new Money(-500000);
assertEquals(expectStockHolderEquity, generator.total.equity);
}
@Override
protected void setUp() throws Exception {
world = new WorldImpl(10, 10);
player = new Player("Player X", world.getNumberOfPlayers());
world.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
world.setTime(new GameTime(0));
Move addPlayerMove = AddPlayerMove.generateMove(world, player);
MoveStatus ms = addPlayerMove.doMove(world, player.getPrincipal());
assertTrue(ms.message, ms.ok);
world.setTime(new GameTime(100));
}
}

IncomeStatementGeneratorTest

Full name: jfreerails.client.view.IncomeStatementGeneratorTest

Documentation

/**
* JUnit test for IncomeStatementGenerator.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test for IncomeStatementGenerator.
*
* @author Luke
*
*/
public class IncomeStatementGeneratorTest extends TestCase {
World w;
IncomeStatementGenerator balanceSheetGenerator;
public void testCalExpense() {
Categories mail = Categories.Mail;
Money m = balanceSheetGenerator.calRevenue(mail);
assertEquals(0, m.getAmount());
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, 0);
assertEquals(mail, ct.getCategory());
Money amount = new Money(100);
addTrans(mail, amount);
addTrans(Categories.Passengers, amount);
m = balanceSheetGenerator.calRevenue(mail);
assertEquals(amount, m);
}
private void addTrans(Categories category, Money amount) {
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, i);
if (ct.getCategory().equals(category)) {
CargoBatch cb = new CargoBatch(i, 0, 0, 0, 0);
w.addTransaction(MapFixtureFactory.TEST_PRINCIPAL,
new DeliverCargoReceipt(amount, 10, 0, cb, 1));
return;
}
}
throw new IllegalArgumentException(category.toString());
}
@Override
protected void setUp() throws Exception {
w = new WorldImpl();
w.addPlayer(MapFixtureFactory.TEST_PLAYER);
MapFixtureFactory.generateCargoTypesList(w);
balanceSheetGenerator = new IncomeStatementGenerator(w,
MapFixtureFactory.TEST_PRINCIPAL);
}
}

TrainScheduleJPanelTest

Full name: jfreerails.client.view.TrainScheduleJPanelTest

Documentation

/**
* Test class for the TrainScheduleJPanel component, focusing on addressing
* the unexpected exception reported in bug 1384249. This class provides
* test methods to validate the behavior of the TrainScheduleJPanel under
* specific conditions.
*
* @see TrainScheduleJPanel
* @see TestCase
*
* @since 1.0
*/

Source Code

public class TrainScheduleJPanelTest extends TestCase {
TrainScheduleJPanel jpanel;
@Override
protected void setUp() throws Exception {
//jpanel = new TrainScheduleJPanel();
//World w = MapFixtureFactory2.getCopy();
}
/*
* [ 1384249 ] Unexpected Exception: TrainScheduleJPanel.java line 661
*/
public void testBug1384249(){
}
}

HtmlJPanelTest

Full name: jfreerails.client.view.HtmlJPanelTest

Documentation

/**
* Tests the populateTokens method on HtmlJPanel.
*
* @author Luke
*
*/

Source Code

/**
* Tests the populateTokens method on HtmlJPanel.
*
* @author Luke
*
*/
public class HtmlJPanelTest extends TestCase {
public void testPopulateTokens() {
String template = "test";
HashMap<String, String> context = new HashMap<String, String>();
String output = HtmlJPanel.populateTokens(template, context);
assertEquals(template, output);
template = "Hello $name$, $question$";
context.put("name", "Luke");
context.put("question", "how are you?");
String expectedOutput = "Hello Luke, how are you?";
output = HtmlJPanel.populateTokens(template, context);
assertEquals(expectedOutput, output);
Object objectContext = new Object() {
@SuppressWarnings("unused")
public String name = "Luke";
@SuppressWarnings("unused")
public String question = "how are you?";
};
output = HtmlJPanel.populateTokens(template, objectContext);
assertEquals(expectedOutput, output);
}
public void testPopulateTokens2(){
String template = "Hey $a.name$ I would like you to meet $b.name$";
String expectedOutput = "Hey Tom I would like you to meet Claire";
Object objectContext = new Object() {
@SuppressWarnings("unused")
public Person a = new Person("Tom");
@SuppressWarnings("unused")
public Person b = new Person("Claire");
};
String output = HtmlJPanel.populateTokens(template, objectContext);
assertEquals(expectedOutput, output);
}
public static class Person{
public String name;
public Person(String name){
this.name = name;
}
}
}

BrokerScreenGeneratorTest

Full name: jfreerails.client.view.BrokerScreenGeneratorTest

Documentation

/**
* Test class for verifying the correctness of the BrokerScreenGenerator
* under scenarios involving stock transactions. This test specifically
* aims to reproduce and validate fixes for bug [1341365], where an exception
* occurred when calculating stock prices after buying shares.
*
* @author John Doe
* @see BrokerScreenGenerator
* @see StockPriceCalculator
*/

Source Code

public class BrokerScreenGeneratorTest extends TestCase {
private World world;
int playerID;
FreerailsPrincipal principal;
@Override
protected void setUp() throws Exception {
// TODO Auto-generated method stub
super.setUp();
world = new WorldImpl(10, 10);
// Set the time..
world.set(ITEM.CALENDAR, new GameCalendar(12000, 1840));
Player p = MapFixtureFactory.TEST_PLAYER;
AddPlayerMove apm = AddPlayerMove.generateMove(world, p);
MoveStatus ms = apm.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.isOk());
playerID = world.getNumberOfPlayers() - 1;
principal = p.getPrincipal();
}
/**
* Testcase to reproduce bug [ 1341365 ] Exception when calculating stock
* price after buying shares
*/
public void testBuyingStock() {
for (int i = 0; i < 9; i++) {
StockPrice stockPrice = new StockPriceCalculator(world).calculate()[playerID];
Money sharePrice = stockPrice.treasuryBuyPrice;
StockTransaction t = StockTransaction.buyOrSellStock(playerID,
StockTransaction.STOCK_BUNDLE_SIZE, sharePrice);
Move move = new AddTransactionMove(principal, t);
MoveStatus ms = move.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.isOk());
//The line below threw an exception that caused bug 1341365.
BrokerScreenGenerator brokerScreenGenerator = new BrokerScreenGenerator(world, principal);
assertNotNull(brokerScreenGenerator);
}
}
}

ImageManagerImplTest

Full name: jfreerails.client.common.ImageManagerImplTest

Documentation

/**
* @author Luke
*
*/

Source Code

/**
* @author Luke
*
*/
public class ImageManagerImplTest extends TestCase {
public void testIsValid() {
assertTrue(ImageManagerImpl.isValid("cursor/infomode.png"));
assertFalse(ImageManagerImpl.isValid("/cursor/infomode.png"));
}
}

Methods

BinaryNumberFormatterTest

Full name: jfreerails.client.common.BinaryNumberFormatterTest

Documentation

/**
* This class formats and integer as a binary number with a specified number of
* digits.
*
* @author Luke Lindsay 03-Nov-2002
*
*/

Source Code

/**
* This class formats and integer as a binary number with a specified number of
* digits.
*
* @author Luke Lindsay 03-Nov-2002
*
*/
public class BinaryNumberFormatterTest extends TestCase {
public BinaryNumberFormatterTest(String arg0) {
super(arg0);
}
public void testBinaryFormat() {
assertEquals("0", BinaryNumberFormatter.format(0, 1));
assertEquals("1", BinaryNumberFormatter.format(1, 1));
assertEquals("00", BinaryNumberFormatter.format(0, 2));
assertEquals("01", BinaryNumberFormatter.format(1, 2));
assertEquals("10", BinaryNumberFormatter.format(2, 2));
assertEquals("11", BinaryNumberFormatter.format(3, 2));
assertEquals("1111", BinaryNumberFormatter.format(15, 4));
try {
BinaryNumberFormatter.format(-1, 2);
assertTrue(false);
} catch (IllegalArgumentException e) {
}
try {
BinaryNumberFormatter.format(4, 2);
assertTrue(false);
} catch (IllegalArgumentException e) {
}
}
}

BuildTrackControllerTest

Full name: jfreerails.client.renderer.BuildTrackControllerTest

Documentation

/** Unit test for BuildTrackController. */

Source Code

/** Unit test for BuildTrackController. */
public class BuildTrackControllerTest extends TestCase {
World w;
ModelRootImpl modelRoot;
BuildTrackController buildTrackController;
TrackMoveProducer trackBuilder;
int singleTrackRuleID = -1;
int doubleTrackRuleID = -1;
@Override
protected void setUp() throws Exception {
w = MapFixtureFactory2.getCopy();
modelRoot = new ModelRootImpl();
FreerailsPrincipal p = w.getPlayer(0).getPrincipal();
modelRoot.setup(w, p);
buildTrackController = new BuildTrackController(w, modelRoot);
MoveExecutor executor = new SimpleMoveExecutor(w, 0);
trackBuilder = new TrackMoveProducer(executor, w, modelRoot);
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
final Integer ruleID = new Integer(i);
TrackRule rule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
if (rule.getTypeName().equals("standard track")) {
singleTrackRuleID = ruleID;
}
if (rule.getTypeName().equals("double track")) {
doubleTrackRuleID = ruleID;
}
}
assertFalse(singleTrackRuleID == -1);
assertFalse(doubleTrackRuleID == -1);
// unit tests should be silent!
modelRoot.setProperty(Property.PLAY_SOUNDS, false);
}
public void testBuildTrack() {
ImPoint from = new ImPoint(10, 10);
modelRoot.setProperty(Property.CURSOR_POSITION, from);
ImPoint to = new ImPoint(20, 10);
buildTrackController.setProposedTrack(to, trackBuilder);
buildTrackController.updateUntilComplete();
assertTrue(buildTrackController.isBuildTrackSuccessful());
// See if any track has actually been built.
FreerailsTile tile = (FreerailsTile) w.getTile(10, 10);
assertFalse(tile.hasTrack());
buildTrackController.updateWorld(trackBuilder);
tile = (FreerailsTile) w.getTile(10, 10);
assertTrue(tile.hasTrack());
tile = (FreerailsTile) w.getTile(20, 10);
assertTrue(tile.hasTrack());
}
public void testUpgradeTrack() {
// Build the track.
testBuildTrack();
// Change the strategy.
BuildTrackStrategy bts = BuildTrackStrategy.getSingleRuleInstance(
doubleTrackRuleID, modelRoot.getWorld());
trackBuilder.setBuildTrackStrategy(bts);
trackBuilder.setTrackBuilderMode(BuildMode.UPGRADE_TRACK);
// Upgrade part of the track.
modelRoot.setProperty(Property.CURSOR_POSITION, new ImPoint(15, 10));
buildTrackController
.setProposedTrack(new ImPoint(20, 10), trackBuilder);
buildTrackController.updateUntilComplete();
assertTrue(buildTrackController.isBuildTrackSuccessful());
buildTrackController.updateWorld(trackBuilder);
FreerailsTile tile = (FreerailsTile) w.getTile(10, 10);
assertEquals(singleTrackRuleID, tile.getTrackPiece().getTrackTypeID());
tile = (FreerailsTile) w.getTile(15, 10);
assertEquals(doubleTrackRuleID, tile.getTrackPiece().getTrackTypeID());
tile = (FreerailsTile) w.getTile(17, 10);
assertEquals(doubleTrackRuleID, tile.getTrackPiece().getTrackTypeID());
tile = (FreerailsTile) w.getTile(20, 10);
assertEquals(doubleTrackRuleID, tile.getTrackPiece().getTrackTypeID());
}
public void testRemoveTrack() {
// Build the track.
testBuildTrack();
// Then remove some of it.
trackBuilder.setTrackBuilderMode(BuildMode.REMOVE_TRACK);
ImPoint from = new ImPoint(15, 10);
modelRoot.setProperty(Property.CURSOR_POSITION, from);
ImPoint to = new ImPoint(20, 10);
buildTrackController.setProposedTrack(to, trackBuilder);
buildTrackController.updateUntilComplete();
assertTrue(buildTrackController.isBuildTrackSuccessful());
buildTrackController.updateWorld(trackBuilder);
}
}

SquareTileBackgroundRendererTest

Full name: jfreerails.client.renderer.SquareTileBackgroundRendererTest

Documentation

/**
* Test class for verifying the behavior of SquareTileBackgroundRenderer
* when refresh operations are performed before the buffer is initialized.
* This test case reproduces bug [1303162] where an unexpected exception occurs
* due to premature refresh calls.
*
* @author John Doe
* @since 1.0
*
* @see SquareTileBackgroundRenderer
* @see MapLayerRenderer
*/

Source Code

public class SquareTileBackgroundRendererTest extends TestCase {
MapLayerRenderer renderer = new MapLayerRenderer(){
public void paintTile(Graphics g, int tileX, int tileY) {
}
public void refreshTile(int x, int y) {
}
public void refreshAll() {
}
public void paintRect(Graphics g, Rectangle visibleRect) {
}
};
/** Testcase to reproduce bug [ 1303162 ] Unexpected Exception:*/
public void testRefreshBeforeBufferIsSet(){
SquareTileBackgroundRenderer stbr = new SquareTileBackgroundRenderer(renderer);
stbr.refreshAll();
stbr.refreshTile(1, 2);
}
}

TrainRendererTest

Full name: jfreerails.client.renderer.TrainRendererTest

Documentation

/**
*
* @author Luke
*/

Source Code

/**
*
* @author Luke
*/
public class TrainRendererTest {
public TrainRendererTest() {
}
@Test
public void testTrainImages() {
RenderersRoot rr = new MyRenderersRoot();
TrainImages wagonImages = rr.getWagonImages(0);
assertNotNull(wagonImages);
TrainImages engineImages = rr.getEngineImages(0);
assertNotNull(engineImages);
for (Step step : Step.getList()) {
Image overheadImage = wagonImages.getOverheadImage(step.getID());
assertTrue(overheadImage instanceof BufferedImage);
}
}
@Test
public void testHit1() {
Point wagonCenter = new Point(100, 100);
Point mouseClick = new Point(100, 100);
boolean hit = isHit(wagonCenter, mouseClick, Step.NORTH);
assertTrue(hit);
}
@Test
public void testHit2() {
Point wagonCenter = new Point(100, 100);
Point mouseClick = new Point(90, 100);
boolean hit = isHit(wagonCenter, mouseClick, Step.NORTH);
assertFalse(hit);
}
@Test
public void testHit3() {
Point wagonCenter = new Point(100, 100);
Point mouseClick = new Point(85, 100);
boolean hit = isHit(wagonCenter, mouseClick, Step.NORTH);
assertFalse(hit);
}
@Test
public void testHit4() {
Point wagonCenter = new Point(100, 100);
Point mouseClick = new Point(84, 100);
boolean hit = isHit(wagonCenter, mouseClick, Step.NORTH);
assertFalse(hit);
}
@Test
public void testHit5() {
Point wagonCenter = new Point(100, 100);
Point mouseClick = new Point(96, 100);
boolean hit = isHit(wagonCenter, mouseClick, Step.NORTH);
assertTrue(hit);
}
public boolean isHit(Point wagonCenter, Point mouseClick, Step step) {
List<Map.Entry<Point, Step>> positions = new ArrayList<>();
positions.add(new AbstractMap.SimpleImmutableEntry<>(wagonCenter, step));
RenderersRoot rr = new MyRenderersRoot();
TrainModel train = new TrainModel(0);
TrainRenderer tr = new TrainRenderer(rr);
boolean hit = tr.isHit(mouseClick, train, positions);
return hit;
}
}

MyRenderersRoot

Full name: jfreerails.client.renderer.MyRenderersRoot

Documentation

/**
* The MyRenderersRoot class serves as the root renderer implementation for managing graphical resources
* in a rail simulation application. It provides access to train images and handles image loading through
* the ImageManager. This class implements the RenderersRoot interface and offers basic support for
* retrieving train-related images, though several renderer methods remain unimplemented as stubs.
*
* @author [Author Name]
* @see RenderersRoot
* @see ImageManager
* @see TrainImages
*/

Source Code

class MyRenderersRoot implements RenderersRoot {
static ImageManager imageManager = new ImageManagerImpl("/jfreerails/client/graphics/");
private TrainImages trainImages;
public MyRenderersRoot() {
try {
this.trainImages = new TrainImages(imageManager, "mail");
} catch (IOException ex) {
Logger.getLogger(MyRenderersRoot.class.getName()).log(Level.SEVERE, null, ex);
fail();
}
}
@Override
public TrackPieceRenderer getTrackPieceView(int i) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public TrainImages getWagonImages(int type) {
return this.trainImages;
}
@Override
public TrainImages getEngineImages(int type) {
return this.trainImages;
}
@Override
public boolean validate(ReadOnlyWorld world) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Image getImage(String relativeFilename) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Image getScaledImage(String relativeFilename, int height) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public TileRenderer getTileViewWithNumber(int i) {
throw new UnsupportedOperationException("Not supported yet.");
}
}

CityEconomicModelTest

Full name: jfreerails.server.CityEconomicModelTest

Documentation

/**
* JUnit Test for CityEconomic.
*
* @author Luke
*
*/

Source Code

/**
* JUnit Test for CityEconomic.
*
* @author Luke
*
*/
public class CityEconomicModelTest extends TestCase {
/**
* Tests generating populated CityEconomicModel from cities on the map.
*/
public void testLoadFromMap() {
World w = MapFixtureFactory.getWorld(100, 100);
CityModel newYork = new CityModel("New York", 10, 20);
w.add(SKEY.CITIES, newYork);
CityEconomicModel city = new CityEconomicModel();
city.loadFromMap(w, 0);
assertEquals(0, city.industryTiles.size());
assertEquals(0, city.urbanTiles.size());
assertEquals("A city is a 7*7 area", 49, city.clearTiles.size());
}
/** Tests calculating the utility of a City. */
public void testUtilityCalculation() {
}
}

CargoAtStationsGeneratorTest

Full name: jfreerails.server.CargoAtStationsGeneratorTest

Documentation

/**
* JUnit test for CargoAtStationsGenerator.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test for CargoAtStationsGenerator.
*
* @author Luke
*
*/
public class CargoAtStationsGeneratorTest extends TestCase {
public void testCalculateAmountToAdd() {
CargoAtStationsGenerator cargoGenerator = new CargoAtStationsGenerator();
int amount = cargoGenerator.calculateAmountToAdd(12, 0);
assertEquals(1, amount);
assertCorrectTotalAddedOverYear(0);
assertCorrectTotalAddedOverYear(12);
assertCorrectTotalAddedOverYear(14);
assertCorrectTotalAddedOverYear(140);
assertCorrectTotalAddedOverYear(3);
}
/**
* If, say, 14 units get added each year, some month we should add 1 and
* others we should add 2 such that over the year exactly 14 units get
* added.
*/
private void assertCorrectTotalAddedOverYear(final int unitPerYear) {
CargoAtStationsGenerator cargoGenerator = new CargoAtStationsGenerator();
int amountAddedThisSoFar = 0;
for (int i = 0; i < 12; i++) {
amountAddedThisSoFar += cargoGenerator.calculateAmountToAdd(
unitPerYear, i);
}
assertEquals(unitPerYear, amountAddedThisSoFar);
}
}

TrackMaintenanceMoveGeneratorTest

Full name: jfreerails.server.TrackMaintenanceMoveGeneratorTest

Documentation

/**
* JUnit test for TrackMaintenanceMoveGenerator.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* JUnit test for TrackMaintenanceMoveGenerator.
*
* @author Luke Lindsay
*
*/
public class TrackMaintenanceMoveGeneratorTest extends TestCase {
private World w;
@Override
protected void setUp() throws Exception {
w = new WorldImpl(20, 20);
w.addPlayer(MapFixtureFactory.TEST_PLAYER);
MapFixtureFactory.generateTrackRuleList(w);
}
public void testCalculateNumberOfEachTrackType() {
int[] actual;
int[] expected;
actual = calNumOfEachTrackType();
/*
* actual = ItemsTransactionAggregator.calulateNumberOfEachTrackType(w,
* MapFixtureFactory.TEST_PRINCIPAL, 0);
*/
expected = new int[] { 0, 0, 0 }; // No track has been built yet.
assertTrue(Arrays.equals(expected, actual));
addTrack(0, 10);
actual = calNumOfEachTrackType();
expected = new int[] { 10, 0, 0 };
assertTrue(Arrays.equals(expected, actual));
addTrack(2, 20);
actual = calNumOfEachTrackType();
expected = new int[] { 10, 0, 20 };
assertTrue(Arrays.equals(expected, actual));
}
private int[] calNumOfEachTrackType() {
int[] actual;
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
w, MapFixtureFactory.TEST_PRINCIPAL);
actual = new int[3];
aggregator.setType(0);
actual[0] = aggregator.calculateQuantity();
aggregator.setType(1);
actual[1] = aggregator.calculateQuantity();
aggregator.setType(2);
actual[2] = aggregator.calculateQuantity();
return actual;
}
/**
* Utility method to add the specified number of units of the specified track
* type.
*/
private void addTrack(int trackType, int quantity) {
AddItemTransaction t = new AddItemTransaction(
Transaction.Category.TRACK, trackType, quantity, new Money(
trackType));
w.addTransaction(MapFixtureFactory.TEST_PRINCIPAL, t);
}
}

MapFixtureFactory2Test

Full name: jfreerails.server.MapFixtureFactory2Test

Documentation

/**
*
*
* @author Luke Lindsay
*
*/

Source Code

/**
*
*
* @author Luke Lindsay
*
*/
public class MapFixtureFactory2Test extends TestCase {
World w1;
public void testGetCopy() {
World w2;
w1 = getCopy();
assertNotNull(w1);
w2 = getCopy();
assertNotNull(w2);
assertNotSame(w1, w2);
assertEquals(w1, w2);
}
public void testLists() {
assertTrue(w1.size(SKEY.CARGO_TYPES) > 0);
assertTrue(w1.size(SKEY.TRACK_RULES) > 0);
assertTrue(w1.size(SKEY.TERRAIN_TYPES) > 0);
}
public void testMap() {
assertEquals(w1.getMapWidth(), 50);
assertEquals(w1.getMapWidth(), 50);
}
public void testPlayers() {
assertEquals(4, w1.getNumberOfPlayers());
}
public void testThatStockIsIssued(){
FreerailsPrincipal p = w1.getPlayer(0).getPrincipal();
int stock = 0;
Money cash = w1.getCurrentBalance(p);
assertEquals(new Money(1000000), cash);
int numberOfTransactions = w1.getNumberOfTransactions(p);
assertTrue(numberOfTransactions > 0);
for(int i = 0; i < numberOfTransactions; i++){
Transaction t = w1.getTransaction(p, i);
if(t.getCategory().equals(Transaction.Category.ISSUE_STOCK)){
AddItemTransaction ait = (AddItemTransaction)t;
stock += ait.getQuantity();
}
}
assertEquals(100000, stock);
}
@Override
protected void setUp() throws Exception {
// TODO Auto-generated method stub
super.setUp();
w1 = getCopy();
}
}

AbstractEchoGameServerTestCase

Full name: jfreerails.network.AbstractEchoGameServerTestCase

Documentation

/**
* Test cases that use EchoGameServer should extend this class.
*
* @author Luke
*
*/

Source Code

/**
* Test cases that use EchoGameServer should extend this class.
*
* @author Luke
*
*/
public abstract class AbstractEchoGameServerTestCase extends TestCase {
InetConnectionAccepter server;
EchoGameServer echoGameServer;
final String ipAddress = "127.0.0.1";
@Override
protected synchronized void setUp() throws Exception {
echoGameServer = EchoGameServer.startServer();
/*
* There was a problem that occurred intermittently when the unit tests
* were run as a batch. I think it was to do with reusing ports in quick
* succession. Passing 0 as the port allow us to listen on an
* unspecified port whose number we obtain by calling getLocalPort().
* Since making this change, the problem has not occurred.
*/
server = new InetConnectionAccepter(0, echoGameServer);
Thread serverThread = new Thread(server);
serverThread.start();
}
@Override
protected synchronized void tearDown() throws Exception {
server.stop();
}
}

Methods

InetConnectionTest

Full name: jfreerails.network.InetConnectionTest

Documentation

/**
* Junit test for NewInetConnection.
*
* @author Luke
*
*/

Source Code

/**
* Junit test for NewInetConnection.
*
* @author Luke
*
*/
public class InetConnectionTest extends AbstractEchoGameServerTestCase {
public void testConnecting() {
try {
assertEquals(0, echoGameServer.countOpenConnections());
InetConnection connection = new InetConnection(ipAddress, server
.getLocalPort());
connection.open();
assertEquals(1, echoGameServer.countOpenConnections());
InetConnection connection2 = new InetConnection(ipAddress, server
.getLocalPort());
connection2.open();
assertEquals(2, echoGameServer.countOpenConnections());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
}

Methods

LocalConnectionTest

Full name: jfreerails.network.LocalConnectionTest

Documentation

/**
* JUnit test for NewLocalConnection.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test for NewLocalConnection.
*
* @author Luke
*
*/
public class LocalConnectionTest extends TestCase {
private LocalConnection localConnection;
private final FreerailsSerializable[] EmptyArray = new FreerailsSerializable[0];
public void testReadFromClient() {
FreerailsSerializable[] objectsRead;
try {
objectsRead = localConnection.readFromClient();
assertNotNull(objectsRead);
assertTrue(Arrays.equals(EmptyArray, objectsRead));
Money m = new Money(100);
localConnection.writeToServer(m); // From the client.
objectsRead = localConnection.readFromClient();
FreerailsSerializable[] expectedArray = {m};
assertEquals(expectedArray.length, objectsRead.length);
assertTrue(Arrays.equals(expectedArray, objectsRead));
objectsRead = localConnection.readFromClient();
assertTrue(Arrays.equals(EmptyArray, objectsRead));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
public void testWait() {
try {
Money m = new Money(100);
localConnection.writeToServer(m);
// Since we have just added an object, there is no need to wait.
Object o = localConnection.waitForObjectFromClient();
assertEquals(m, o);
localConnection.writeToClient(m);
o = localConnection.waitForObjectFromServer();
assertEquals(m, o);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
public void testReadFromServer() {
FreerailsSerializable[] objectsRead;
try {
objectsRead = localConnection.readFromServer();
assertNotNull(objectsRead);
assertTrue(Arrays.equals(EmptyArray, objectsRead));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
public void testClose() {
try {
localConnection.disconnect();
Money m = new Money(100);
localConnection.writeToClient(m);
fail();
} catch (Exception e) {
}
}
public void testIsOpen() {
assertTrue(localConnection.isOpen());
}
@Override
protected void setUp() throws Exception {
localConnection = new LocalConnection();
}
}

EchoGameServerTest

Full name: jfreerails.network.EchoGameServerTest

Documentation

/**
* JUnit test for EchoGameServer.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test for EchoGameServer.
*
* @author Luke
*
*/
public class EchoGameServerTest extends AbstractEchoGameServerTestCase {
/**
* Tests connecting to an EchoGameServer using instances of
* InetConnection2Server.
*/
public void testConnecting() {
try {
assertEquals(0, echoGameServer.countOpenConnections());
InetConnection2Server con1 = new InetConnection2Server(ipAddress,
server.getLocalPort());
InetConnection2Server con2 = new InetConnection2Server(ipAddress,
server.getLocalPort());
assertEquals(2, echoGameServer.countOpenConnections());
con1.writeToServer(new Money(99));
con1.flush();
FreerailsSerializable fs = con2.waitForObject();
assertEquals(new Money(99), fs);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
}

Methods

MovePrecommitterTest

Full name: jfreerails.network.specifics.MovePrecommitterTest

Documentation

/**
* @author Luke
*
*/

Source Code

/**
* @author Luke
*
*/
public class MovePrecommitterTest extends TestCase {
private World w;
private MovePrecommitter committer;
@Override
protected void setUp() throws Exception {
w = new WorldImpl(10, 10);
committer = new MovePrecommitter(w);
}
/** Test simple case of precommitting then fully committing moves. */
public void test1() {
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
assertFalse(oldtime.equals(newTime));
Move m = new TimeTickMove(oldtime, newTime);
MoveStatus ms = m.tryDoMove(w, Player.AUTHORITATIVE);
assertTrue(ms.ok);
committer.toServer(m);
/* The move m should now have been precommitted. */
assertEquals(newTime, getTime());
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(1, committer.precomitted.size());
committer.fromServer(ms);
/* The move m should now be full committed. */
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
assertEquals(newTime, getTime());
}
/** Test test clash. */
public void test2() {
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
assertFalse(oldtime.equals(newTime));
Move m = new TimeTickMove(oldtime, newTime);
MoveStatus ms = m.tryDoMove(w, Player.AUTHORITATIVE);
assertTrue(ms.ok);
committer.toServer(m);
/* The move m should now have been precommitted. */
assertEquals(newTime, getTime());
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(1, committer.precomitted.size());
committer.fromServer(m);
assertFalse(m.tryDoMove(w, Player.AUTHORITATIVE).ok);
/* The move m should now be full committed. */
assertEquals(1, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
assertEquals(newTime, getTime());
committer.precommitMoves();
/*
* The committer should be block since the move on the uncommitted list
* fails to go through.
*/
assertTrue(committer.blocked);
assertEquals(1, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
Move m2 = new TimeTickMove(newTime, oldtime);
committer.fromServer(m2);
assertEquals(oldtime, getTime());
committer.fromServer(ms);
assertEquals(newTime, getTime());
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
}
/** Test test rejection 1. */
public void test3() {
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
assertFalse(oldtime.equals(newTime));
Move m = new TimeTickMove(oldtime, newTime);
MoveStatus ms = m.tryDoMove(w, Player.AUTHORITATIVE);
assertTrue(ms.ok);
committer.toServer(m);
/* The move m should now have been precommitted. */
assertEquals(newTime, getTime());
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(1, committer.precomitted.size());
/* Now, suppose the server rejected the move.. */
MoveStatus rejection = MoveStatus.moveFailed("Rejected!");
committer.fromServer(rejection);
assertEquals(oldtime, getTime());
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
}
/** Test test rejection 2. */
public void test4() {
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
assertFalse(oldtime.equals(newTime));
/* the following move should fail! */
Move m = new TimeTickMove(newTime, oldtime);
MoveStatus ms = m.tryDoMove(w, Player.AUTHORITATIVE);
assertFalse(ms.ok);
committer.toServer(m);
assertTrue(committer.blocked);
assertEquals(1, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
committer.fromServer(ms);
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
}
public void testPreMoves1() {
PreMove pm = TimeTickPreMove.INSTANCE;
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
committer.fromServer(pm);
assertEquals(newTime, getTime());
}
public void testPreMoves2() {
PreMove pm = TimeTickPreMove.INSTANCE;
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
// Send a premove to the server.
committer.toServer(pm);
assertEquals(0, committer.uncomitted.size());
assertEquals(1, committer.precomitted.size());
assertEquals(newTime, getTime());
// The server accepts it..
committer.fromServer(PreMoveStatus.PRE_MOVE_OK);
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
assertEquals(newTime, getTime());
}
public void testPreMoves3() {
PreMove pm = TimeTickPreMove.INSTANCE;
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
// Send a premove to the server.
committer.toServer(pm);
assertEquals(0, committer.uncomitted.size());
assertEquals(1, committer.precomitted.size());
assertEquals(newTime, getTime());
// The server rejects it.
committer.fromServer(PreMoveStatus.failed("failed"));
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
assertEquals(oldtime, getTime());
}
private GameTime getTime() {
return w.currentTime();
}
}

FreerailsClientTest

Full name: jfreerails.network.specifics.FreerailsClientTest

Documentation

/**
* Tests FreerailsClient with a network server.
*
* @author Luke
*
*/

Source Code

/**
* Tests FreerailsClient with a network server.
*
* @author Luke
*
*/
public class FreerailsClientTest extends AbstractFreerailsServerTestCase {
public void testLogon() {
try {
/* Test 1 : connecting a client. */
assertEquals("No client connected yet.", 0, server
.countOpenConnections());
FreerailsClient client = new FreerailsClient();
LogOnResponse response = client.connect(getIpAddress(), getPort(),
"name", "password");
assertTrue(response.isSuccessful());
assertEquals(1, server.countOpenConnections());
assertMapsAndSaveGamesReceived(client);
assertConnectClientsEquals(client, new ImStringList("name"));
/* Test 2 : a client that has already logged on. */
FreerailsClient client2 = new FreerailsClient();
response = client2.connect(getIpAddress(), getPort(), "name",
"password");
assertFalse("The player is already logged on.", response
.isSuccessful());
assertEquals(1, server.countOpenConnections());
/* Test 3 : connecting a client. */
FreerailsClient client3 = new FreerailsClient();
response = client3.connect(getIpAddress(), getPort(), "name3",
"password");
assertTrue(response.isSuccessful());
assertEquals(2, server.countOpenConnections());
/* read list of connected clients. */
assertConnectClientsEquals(client,
new ImStringList("name", "name3"));
assertMapsAndSaveGamesReceived(client3);
assertConnectClientsEquals(client3, new ImStringList("name",
"name3"));
/* Test 4 : disconnect the client from test 1. */
client.disconnect();
assertEquals(1, server.countOpenConnections());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
private void assertConnectClientsEquals(FreerailsClient client,
ImStringList expectedPlayerNames) throws IOException,
InterruptedException {
Message2Client message2Client = (Message2Client) client.read();
message2Client.execute(client);
ImStringList actualPlayerNames = (ImStringList) client
.getProperty(ClientProperty.CONNECTED_CLIENTS);
assertNotNull(actualPlayerNames);
assertEquals(expectedPlayerNames, actualPlayerNames);
}
private void assertMapsAndSaveGamesReceived(FreerailsClient client)
throws IOException, InterruptedException {
// 2 commands to read.
Message2Client message2Client = (Message2Client) client.read();
message2Client.execute(client);
message2Client = (Message2Client) client.read();
message2Client.execute(client);
Object maps = client.getProperty(ClientProperty.MAPS_AVAILABLE);
assertNotNull(maps);
Object savedGames = client
.getProperty(ClientProperty.SAVED_GAMES);
assertNotNull(savedGames);
}
}

AbstractFreerailsServerTestCase

Full name: jfreerails.network.specifics.AbstractFreerailsServerTestCase

Documentation

/**
* Test cases that use FreerailsGameServer <b>and</b> connect over the Internet
* should extend this class .
*
* @author Luke
*
*/

Source Code

/**
* Test cases that use FreerailsGameServer <b>and</b> connect over the Internet
* should extend this class .
*
* @author Luke
*
*/
public abstract class AbstractFreerailsServerTestCase extends TestCase {
private InetConnectionAccepter connectionAccepter;
protected FreerailsGameServer server;
private final String ipAddress = "127.0.0.1";
@Override
protected synchronized void setUp() throws Exception {
server = FreerailsGameServer
.startServer(new SavedGamesManager4UnitTests());
connectionAccepter = new InetConnectionAccepter(0, server);
Thread serverThread = new Thread(connectionAccepter);
serverThread.start();
}
@Override
protected synchronized void tearDown() throws Exception {
connectionAccepter.stop();
}
protected int getPort() {
return connectionAccepter.getLocalPort();
}
protected String getIpAddress() {
return ipAddress;
}
}

FreerailsClientWithLocalServerTest

Full name: jfreerails.network.specifics.FreerailsClientWithLocalServerTest

Documentation

/**
* This test uses clients connected to a local server. This means anything sent
* to the server arrives instantly, which makes writing the test easier.
*
* @author Luke
* @see FreerailsClientTest
*/

Source Code

/**
* This test uses clients connected to a local server. This means anything sent
* to the server arrives instantly, which makes writing the test easier.
*
* @author Luke
* @see FreerailsClientTest
*/
public class FreerailsClientWithLocalServerTest extends TestCase {
private FreerailsGameServer server;
private SavedGamesManager4UnitTests savedGamesManager;
@Override
protected void setUp() throws Exception {
savedGamesManager = new SavedGamesManager4UnitTests();
server = new FreerailsGameServer(savedGamesManager);
}
/** Copy & pasted from FreerailsClientTest, then edited. */
public void testLogon() {
try {
/* Test 1 : connecting a client. */
assertEquals("No client connected yet.", 0, server
.countOpenConnections());
FreerailsClient client = new FreerailsClient();
LogOnResponse response = client.connect(server, "name", "password");
assertTrue(response.isSuccessful());
assertEquals(1, server.countOpenConnections());
// Check the client gets its properties updated.
client.update();
assertNotNull(client
.getProperty(ClientControlInterface.ClientProperty.CONNECTED_CLIENTS));
assertNotNull(client
.getProperty(ClientControlInterface.ClientProperty.MAPS_AVAILABLE));
assertNotNull(client
.getProperty(ClientControlInterface.ClientProperty.SAVED_GAMES));
/* Test 2 : a client that has already logged on. */
FreerailsClient client1 = new FreerailsClient();
response = client1.connect(server, "name", "password");
assertFalse("The player is already logged on.", response
.isSuccessful());
assertEquals(1, server.countOpenConnections());
/* Test 3 : connecting a client. */
FreerailsClient client3 = new FreerailsClient();
response = client3.connect(server, "name3", "password");
assertTrue(response.isSuccessful());
assertEquals(2, server.countOpenConnections());
/* Test 4 : disconnect the client from test 1. */
client.disconnect();
assertEquals(1, server.countOpenConnections());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
public void testNewGame() {
assertEquals(0, server.countOpenConnections());
/* Connect 2 clients. */
FreerailsClient client0 = new FreerailsClient();
LogOnResponse response0 = client0
.connect(server, "client0", "password");
assertTrue(response0.isSuccessful());
FreerailsClient client1 = new FreerailsClient();
LogOnResponse response1 = client1
.connect(server, "client1", "password");
assertTrue(response1.isSuccessful());
assertEquals(2, server.countOpenConnections());
client0.update();
client1.update();
/* Start a new game. */
assertNull(client0.getWorld());
assertNull(client1.getWorld());
ImStringList mapNames = (ImStringList) client0
.getProperty(ClientProperty.MAPS_AVAILABLE);
final int commandID = 66;
Message2Server message2 = new NewGameMessage2Server(commandID, mapNames
.get(0));
client0.write(message2);
assertTrue(server.isNewPlayersAllowed());
server.update();
assertFalse("New players cannot be added once the game has started.",
server.isNewPlayersAllowed());
/*
* Note, the following would have happened anyway when client0.update();
* gets called.
*/
FreerailsSerializable obj = client0.read();
Message2Client cc = (Message2Client) obj;
client0.write(cc.execute(client0));
obj = client0.read();
MessageStatus status = (MessageStatus) obj;
assertTrue(status.isSuccessful());
assertEquals(commandID, status.getId());
/* The server should have sent a message2 that sets the world object. */
client0.update();
client1.update();
assertNotNull(client0.getWorld());
assertNotNull(client1.getWorld());
/* The server will not have read the players confirmation yet. */
assertFalse(server.isConfirmed(0));
assertFalse(server.isConfirmed(1));
server.update();
/* Now it will. */
assertTrue(server.isConfirmed(0));
assertTrue(server.isConfirmed(1));
/*
* The number of players on the world object should be the same as the
* number of players under the ClientControlInterface.CONNECTED_CLIENTS
* key
*/
int connectedPlayers = ((ImStringList) client0
.getProperty(ClientProperty.CONNECTED_CLIENTS)).size();
int playersOnWorldObject = client0.getWorld().getNumberOfPlayers();
assertEquals(connectedPlayers, playersOnWorldObject);
World w = client0.getWorld();
assertNotNull(w.getPlayer(0));
assertNotNull(w.getPlayer(1));
/*
* Now check that attempts to log on by new players are rejected.
*/
assertEquals(2, server.countOpenConnections());
FreerailsClient client = new FreerailsClient();
LogOnResponse response = client.connect(server, "Late player",
"password");
assertFalse(response.isSuccessful());
assertEquals(2, server.countOpenConnections());
}
/** Tests sending moves between client and server. */
public void testSendingMoves() {
try {
/* Set up and start a game with 2 clients. */
FreerailsClient client0 = new FreerailsClient();
LogOnResponse response0 = client0.connect(server, "client0",
"password");
assertTrue(response0.isSuccessful());
FreerailsClient client1 = new FreerailsClient();
LogOnResponse response1 = client1.connect(server, "client1",
"password");
assertTrue(response1.isSuccessful());
client0.update();
client1.update();
ImStringList mapNames = (ImStringList) client0
.getProperty(ClientProperty.MAPS_AVAILABLE);
Message2Server message2 = new NewGameMessage2Server(99, mapNames
.get(0));
client0.write(message2);
server.update();
client0.update();
client1.update();
/* Now try sending some moves. */
World world = client0.getWorld();
Player player0 = world.getPlayer(0);
FreerailsPrincipal principal0 = player0.getPrincipal();
Transaction t = new Receipt(new Money(100),
Transaction.Category.MISC_INCOME);
Move move = new AddTransactionMove(principal0, t);
World copyOfWorld = world.defensiveCopy();
assertEquals(copyOfWorld, world);
MoveStatus status = move.doMove(copyOfWorld, principal0);
assertTrue(status.isOk());
// client0.write(move);
client0.processMove(move);
server.update();
MoveStatus reply = (MoveStatus) client0.read();
assertEquals(MoveStatus.MOVE_OK, reply);
client0.processMessage(reply);
/*
* After performing an update, the server and 2 clients' copies of
* the world object should be in the same state.
*/
server.update();
client0.update();
client1.update();
assertEquals(copyOfWorld, world);
assertEquals(copyOfWorld, client1.getWorld());
assertEquals(copyOfWorld, server.getCopyOfWorld());
/* Test disconnecting and reconnecting during play. */
client0.disconnect();
client1.processMove(move);
// client1.write(move);
move.doMove(client1.getWorld(), principal0);
client1.update();
server.update();
client1.update();
assertFalse(world.equals(client1.getWorld()));
response0 = client0.connect(server, "client0", "password");
assertTrue(response0.isSuccessful());
assertEquals(0, response0.getPlayerID());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
/** Tests sending premoves between client and server. */
public void testSendingPreMoves() {
try {
/* Set up and start a game with 2 clients. */
FreerailsClient client0 = new FreerailsClient();
LogOnResponse response0 = client0.connect(server, "client0",
"password");
assertTrue(response0.isSuccessful());
FreerailsClient client1 = new FreerailsClient();
LogOnResponse response1 = client1.connect(server, "client1",
"password");
assertTrue(response1.isSuccessful());
client0.update();
client1.update();
ImStringList mapNames = (ImStringList) client0
.getProperty(ClientProperty.MAPS_AVAILABLE);
Message2Server message2 = new NewGameMessage2Server(99, mapNames
.get(0));
client0.write(message2);
server.update();
client0.update();
client1.update();
/* Now try sending some premoves. */
Player player0 = client0.getWorld().getPlayer(0);
FreerailsPrincipal principal0 = player0.getPrincipal();
PreMove pm = TimeTickPreMove.INSTANCE;
World copyOfWorld = client0.getWorld().defensiveCopy();
assertEquals(copyOfWorld, client0.getWorld());
Move move = pm.generateMove(copyOfWorld);
MoveStatus status = move.doMove(copyOfWorld, principal0);
assertTrue(status.isOk());
client0.processPreMove(pm);
server.update();
PreMoveStatus reply = (PreMoveStatus) client0.read();
assertEquals(PreMoveStatus.PRE_MOVE_OK, reply);
client0.processMessage(reply);
server.update();
client0.update();
client1.update();
assertEquals(copyOfWorld, client0.getWorld());
assertEquals(copyOfWorld, client1.getWorld());
assertEquals(copyOfWorld, server.getCopyOfWorld());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
public void testLoadingGame() {
try {
int commandID = 0;
// Add client to server.
FreerailsClient client0 = new FreerailsClient();
LogOnResponse response0 = client0.connect(server, "client0",
"password");
assertTrue(response0.isSuccessful());
client0.update();
// Start game
ImStringList mapNames = (ImStringList) client0
.getProperty(ClientProperty.MAPS_AVAILABLE);
Message2Server newGameMessage2 = new NewGameMessage2Server(
commandID++, mapNames.get(0));
MessageStatus cm = newGameMessage2.execute(server);
assertTrue(cm.isSuccessful());
// Save game and stop server
String savedGameName = "game1";
Message2Server saveGameMessage2 = new SaveGameMessage2Server(
commandID++, savedGameName);
cm = saveGameMessage2.execute(server);
assertTrue(cm.isSuccessful());
server.stopGame();
// Start 2nd server with saved game
server = new FreerailsGameServer(savedGamesManager);
server.loadgame(savedGameName);
assertEquals(0, server.countOpenConnections());
// Attempt to attach invalid player.
client0 = new FreerailsClient();
response0 = client0.connect(server, "client0", "batman");
assertFalse("bad password", response0.isSuccessful());
assertEquals(0, server.countOpenConnections());
response0 = client0.connect(server, "client1", "password");
assertFalse("bad username", response0.isSuccessful());
assertEquals(0, server.countOpenConnections());
response0 = client0.connect(server, "client0", "password");
assertTrue("Ok, same username and password as before.", response0
.isSuccessful());
assertEquals(1, server.countOpenConnections());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}
}

FreerailsGameServerTest

Full name: jfreerails.network.specifics.FreerailsGameServerTest

Documentation

/**
* Junit test for FreerailsGameServer - tests logging on.
*
* @author Luke
*
*/

Source Code

/**
* Junit test for FreerailsGameServer - tests logging on.
*
* @author Luke
*
*/
public class FreerailsGameServerTest extends TestCase {
private FreerailsGameServer server;
public void testLogon() {
LogOnResponse response;
/* Test 1 */
LogOnRequest request1 = new LogOnRequest("Name", "password");
response = server.logon(request1);
assertTrue("Simple case, should go through.", response.isSuccessful());
assertEquals("1st logon is player 0", 0, response.getPlayerID());
/* Test 2 */
LogOnRequest request2 = new LogOnRequest("Name2", "password2");
response = server.logon(request2);
assertTrue("Simple case, should go through.", response.isSuccessful());
assertEquals("2nd logon is player 1", 1, response.getPlayerID());
/* Test 3: When player is already logged on. */
LogOnRequest request3 = new LogOnRequest("Name", "password");
response = server.logon(request3);
assertFalse("Player is already logged on.", response.isSuccessful());
/* Test 4: When new logons are not allowed. */
server.setNewPlayersAllowed(false);
LogOnRequest request4 = new LogOnRequest("Name4", "password4");
response = server.logon(request4);
assertFalse("New logons are not allowed.", response.isSuccessful());
/* Test 5: When the player has logged off, then tries to log on. */
server.logoff(0);
LogOnRequest request5 = request1;
response = server.logon(request5);
assertTrue("Player 0 has logged off, so should succeed.", response
.isSuccessful());
assertEquals("Should keep the same player id", 0, response
.getPlayerID());
/*
* Test 6: When the player has logged off, then tries to log on with
* wrong password.
*/
server.logoff(0);
LogOnRequest request6 = new LogOnRequest("Name", "batman");
response = server.logon(request6);
assertFalse("Player 0 has logged off, but the password is wrong.",
response.isSuccessful());
}
@Override
protected void setUp() throws Exception {
server = new FreerailsGameServer(new SavedGamesManager4UnitTests());
}
}

Methods

FinancialDataGathererTest

Full name: jfreerails.controller.FinancialDataGathererTest

Documentation

/**
* JUnit test for FinancialDataGatherer.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test for FinancialDataGatherer.
*
* @author Luke
*
*/
public class FinancialDataGathererTest extends TestCase {
World w;
Player player;
@Override
protected void setUp() throws Exception {
player =new Player("Player X", 0);
w = new WorldImpl();
Move addPlayer = AddPlayerMove.generateMove(w, player);
MoveStatus ms = addPlayer.doMove(w, Player.AUTHORITATIVE);
assertTrue(ms.ok);
}
public void testCanIssueBond() {
FinancialDataGatherer fdg = new FinancialDataGatherer(w, player
.getPrincipal());
assertTrue(fdg.canIssueBond()); // 5%
assertTrue(addBond()); // 6%
assertTrue(addBond()); // 7%
assertFalse(addBond()); // 8% so can't
fdg = new FinancialDataGatherer(w, player.getPrincipal());
assertEquals(8, fdg.nextBondInterestRate());
}
/**
* Adds a bond and returns true if another bond can be added. Written to
* avoid copy & paste in testCanIssueBond().
*/
private boolean addBond() {
FinancialDataGatherer fdg;
w.addTransaction(player.getPrincipal(), BondTransaction.issueBond(5));
fdg = new FinancialDataGatherer(w, player.getPrincipal());
boolean canIssueBond = fdg.canIssueBond();
return canIssueBond;
}
public void testNextBondInterestRate() {
FinancialDataGatherer fdg = new FinancialDataGatherer(w, player
.getPrincipal());
assertEquals(5, fdg.nextBondInterestRate());
w.addTransaction(player.getPrincipal(), BondTransaction.issueBond(5));
fdg = new FinancialDataGatherer(w, player.getPrincipal());
assertEquals(6, fdg.nextBondInterestRate());
}
public void testTreasuryStock() {
FreerailsPrincipal principal = player.getPrincipal();
FinancialDataGatherer fdg = new FinancialDataGatherer(w, principal);
assertEquals(0, fdg.treasuryStock());
int treasuryStock = 10000;
int totalStock = FinancialMoveProducer.IPO_SIZE;
int publicStock = totalStock - treasuryStock;
Transaction t = StockTransaction.buyOrSellStock(0, treasuryStock, new Money(5));
w.addTransaction(principal, t);
fdg = new FinancialDataGatherer(w, principal);
assertEquals(treasuryStock,
fdg.treasuryStock());
assertEquals(totalStock,
fdg.totalShares());
assertEquals(publicStock,
fdg.sharesHeldByPublic());
}
public void testBuyingStakesInOtherRRs(){
w = new WorldImpl();
Player[] players = new Player[2];
for(int i = 0; i < players.length; i++){
players[i] = new Player("Player "+i, i);
Move addPlayer = AddPlayerMove.generateMove(w, players[i]);
MoveStatus ms = addPlayer.doMove(w, Player.AUTHORITATIVE);
assertTrue(ms.ok);
}
//Make player #0 buy stock in player #1
int quantity = 10000;
Transaction t = StockTransaction.buyOrSellStock(1, quantity, new Money(5));
w.addTransaction(players[0].getPrincipal(), t);
FinancialDataGatherer fdg = new FinancialDataGatherer(w, players[0].getPrincipal());
assertEquals(0, fdg.treasuryStock());
int actual = fdg.getStockInRRs()[1];
assertEquals(quantity, actual);
}
public void testTotalShares() {
FinancialDataGatherer fdg = new FinancialDataGatherer(w, player
.getPrincipal());
int expected = FinancialMoveProducer.IPO_SIZE;
assertEquals(expected, fdg.totalShares());
}
}

SharePriceCalculatorTest

Full name: jfreerails.controller.SharePriceCalculatorTest

Documentation

/**
* @author Luke
*
*/

Source Code

/**
* @author Luke
*
*/
public class SharePriceCalculatorTest extends TestCase {
public void test1() {
SharePriceCalculator cal = new SharePriceCalculator();
cal.networth = 100000;
cal.profitsLastYear = 100000;
cal.stockholderEquity = 500000;
cal.totalShares = 100000;
long expected = (100000 + 500000 + 100000 * 5) / 100000;
assertEquals(expected, cal.calculatePrice());
}
}

Methods

PathOnTrackFinderTest

Full name: jfreerails.controller.PathOnTrackFinderTest

Documentation

/**
* @author Luke
*
*/

Source Code

/**
* @author Luke
*
*/
public class PathOnTrackFinderTest extends TestCase {
World w;
TrackMoveProducer producer;
PathOnTrackFinder pathFinder;
StationBuilder stationBuilder;
BuildTrackStrategy bts;
@Override
protected void setUp() throws Exception {
super.setUp();
w = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(w, 0);
ModelRoot mr = new ModelRootImpl();
producer = new TrackMoveProducer(me, w, mr);
pathFinder = new PathOnTrackFinder(w);
stationBuilder = new StationBuilder(me);
bts = BuildTrackStrategy.getDefault(w);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testPathAsVectors1() {
Step[] path = { EAST, EAST, SOUTH_EAST };
ImPoint start = new ImPoint(5, 5);
ImPoint end = Step.move(start, path);
producer.buildTrack(start, path);
try {
pathFinder.setupSearch(start, end);
pathFinder.search(-1);
assertEquals(IncrementalPathFinder.PATH_FOUND, pathFinder
.getStatus());
Step[] pathFound = pathFinder.pathAsVectors();
assertTrue(Arrays.equals(path, pathFound));
} catch (PathNotFoundException e) {
fail();
}
}
public void testPathAsVectors2() {
Step[] path = { EAST, EAST, SOUTH_EAST, EAST, EAST, NORTH_EAST };
ImPoint start = new ImPoint(5, 5);
ImPoint end = Step.move(start, path);
producer.buildTrack(start, path);
try {
pathFinder.setupSearch(start, end);
pathFinder.search(-1);
assertEquals(IncrementalPathFinder.PATH_FOUND, pathFinder
.getStatus());
Step[] pathFound = pathFinder.pathAsVectors();
assertTrue(Arrays.equals(path, pathFound));
} catch (PathNotFoundException e) {
fail();
}
}
public void testSetupSearch() {
Step[] path = { EAST, EAST, SOUTH_EAST };
ImPoint start = new ImPoint(5, 5);
ImPoint end = Step.move(start, path);
producer.buildTrack(start, path);
try {
pathFinder.setupSearch(start, end);
} catch (PathNotFoundException e) {
fail("Track at both of the points so no exception should be thrown");
}
try {
pathFinder.setupSearch(start, new ImPoint(10, 10));
fail("No track at one of the points so an exception should be thrown");
} catch (PathNotFoundException e) {
}
try {
pathFinder.setupSearch(new ImPoint(10, 10), end);
fail("No track at one of the points so an exception should be thrown");
} catch (PathNotFoundException e) {
}
}
}

MoveTrainPreMove1stTest

Full name: jfreerails.controller.MoveTrainPreMove1stTest

Documentation

/**
* JUnit test for MoveTrainPreMove, tests moving round a loop of track.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test for MoveTrainPreMove, tests moving round a loop of track.
*
* @author Luke
*
*/
public class MoveTrainPreMove1stTest extends AbstractMoveTestCase {
TrackMoveProducer trackBuilder;
StationBuilder stationBuilder;
FreerailsPrincipal principal;
private ImPoint stationA;
private ImPoint stationB;
ImmutableSchedule defaultSchedule;
@Override
protected void setupWorld() {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
trackBuilder = new TrackMoveProducer(me, world, mr);
stationBuilder = new StationBuilder(me);
// Build track.
stationBuilder
.setStationType(stationBuilder.getTrackTypeID("terminal"));
Step[] track = { EAST, EAST, EAST, EAST, EAST, EAST, EAST, EAST, EAST };
stationA = new ImPoint(10, 10);
MoveStatus ms0 = trackBuilder.buildTrack(stationA, track);
assertTrue(ms0.ok);
// Build 2 stations.
MoveStatus ms1 = stationBuilder.buildStation(stationA);
assertTrue(ms1.ok);
stationB = new ImPoint(19, 10);
MoveStatus ms2 = stationBuilder.buildStation(stationB);
assertTrue(ms2.ok);
TrainOrdersModel order0 = new TrainOrdersModel(1, null, false, false);
TrainOrdersModel order1 = new TrainOrdersModel(0, null, false, false);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
defaultSchedule = s.toImmutableSchedule();
ImPoint start = new ImPoint(10, 10);
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0),
start, principal, defaultSchedule);
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, principal);
assertTrue(ms.ok);
}
public void testNextVector() {
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
Step actual = preMove.nextStep(world);
assertNotNull(actual);
// The train is at station A, so should head east to station B.
assertEquals(EAST, actual);
}
public void testNextSpeeds() {
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
SpeedAgainstTime speeds = preMove.nextSpeeds(world, EAST);
assertNotNull(speeds);
assertEquals(speeds.calcV(0), 0d);
assertTrue(speeds.getS() >= EAST.getLength());
double t = speeds.getT();
assertTrue(t > 0);
assertTrue(speeds.calcV(t) > 0);
}
@Override
public void testMove() {
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
Move m = preMove.generateMove(world);
assertNotNull(m);
assertSurvivesSerialisation(m);
}
public void testMove2() {
MoveStatus ms;
Move m;
setupLoopOfTrack();
TrainAccessor ta = new TrainAccessor(world, principal, 0);
TrainMotion tm = ta.findCurrentMotion(3);
assertEquals(0d, tm.duration());
PathOnTiles expected = new PathOnTiles(new ImPoint(5, 5), SOUTH_WEST);
assertEquals(expected, tm.getPath());
PositionOnTrack pot = tm.getFinalPosition();
int x = pot.getX();
assertEquals(4, x);
int y = pot.getY();
assertEquals(6, y);
assertEquals(SOUTH_WEST, pot.facing());
MoveTrainPreMove moveTrain = new MoveTrainPreMove(0, principal);
assertEquals(NORTH_EAST, moveTrain.nextStep(world));
m = moveTrain.generateMove(world);
ms = m.doMove(world, principal);
assertTrue(ms.ok);
TrainMotion tm2 = ta.findCurrentMotion(3);
assertFalse(tm.equals(tm2));
expected = new PathOnTiles(new ImPoint(5, 5), SOUTH_WEST, NORTH_EAST);
assertEquals(expected, tm2.getPath());
assertTrue(tm2.duration() > 3d);
// The expected value is 3.481641930846211, found from
// stepping thu code in debugger.
assertTrackHere(tm2.getTiles(tm2.duration()));
pot = tm2.getFinalPosition();
assertEquals(4, x);
assertEquals(6, y);
// assertEquals(SOUTH, pot.facing());
assertTrackHere(x, y);
assertEquals(EAST, moveTrain.nextStep(world));
MoveTrainPreMove2ndTest.incrTime(world, principal);
m = moveTrain.generateMove(world);
ms = m.doMove(world, principal);
assertTrue(ms.ok);
TrainMotion tm3 = ta.findCurrentMotion(100);
assertFalse(tm3.equals(tm2));
expected = new PathOnTiles(new ImPoint(4, 6), NORTH_EAST, EAST);
assertEquals(expected, tm3.getPath());
assertTrackHere(tm3.getTiles(tm3.duration()));
assertTrackHere(tm3.getTiles(tm3.duration() / 2));
assertTrackHere(tm3.getTiles(0));
assertTrackHere(tm3.getPath());
assertEquals(SOUTH_EAST, moveTrain.nextStep(world));
MoveTrainPreMove2ndTest.incrTime(world, principal);
m = moveTrain.generateMove(world);
ms = m.doMove(world, principal);
assertTrue(ms.ok);
}
private void setupLoopOfTrack() {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
TrackMoveProducer producer = new TrackMoveProducer(me, world, mr);
Step[] trackPath = { EAST, SOUTH_EAST, SOUTH, SOUTH_WEST, WEST,
NORTH_WEST, NORTH, NORTH_EAST };
ImPoint from = new ImPoint(5, 5);
MoveStatus ms = producer.buildTrack(from, trackPath);
assertTrue(ms.ok);
TrainOrdersModel[] orders = {};
ImmutableSchedule is = new ImmutableSchedule(orders, -1, false);
AddTrainPreMove addTrain = new AddTrainPreMove(0, new ImInts(), from,
principal, is);
Move m = addTrain.generateMove(world);
ms = m.doMove(world, principal);
assertTrue(ms.ok);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
TrainMotion motion = ta.findCurrentMotion(0);
assertNotNull(motion);
PathOnTiles expected = new PathOnTiles(from, SOUTH_WEST);
PathOnTiles actual = motion.getTiles(motion.duration());
assertEquals(expected, actual);
}
public void testMovingRoundLoop() {
setupLoopOfTrack();
MoveTrainPreMove moveTrain = new MoveTrainPreMove(0, principal);
Move m = moveTrain.generateMove(world);
assertTrue(m.doMove(world, principal).ok);
}
public void testGetTiles() {
setupLoopOfTrack();
MoveTrainPreMove moveTrain = new MoveTrainPreMove(0, principal);
Move m = moveTrain.generateMove(world);
assertTrue(m.doMove(world, principal).ok);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
TrainMotion motion = ta.findCurrentMotion(1);
double duration = motion.duration();
assertTrue(duration > 1);
int trainLength = motion.getTrainLength();
for (int i = 0; i < 10; i++) {
double t = i == 0 ? 0 : duration * i / 10;
PathOnTiles tiles = motion.getTiles(t);
assertTrue("t=" + t, tiles.steps() > 0);
assertTrue("t=" + t, tiles.getTotalDistance() >= trainLength);
}
}
public void testFindNextVector() {
setupLoopOfTrack();
PositionOnTrack pot = PositionOnTrack.createFacing(4, 6, SOUTH_WEST);
ImPoint target = new ImPoint();
Step expected = NORTH_EAST;
assertEquals(expected, MoveTrainPreMove.findNextStep(world, pot,
target));
pot.move(expected);
expected = EAST;
assertEquals(expected, MoveTrainPreMove.findNextStep(world, pot,
target));
pot.move(expected);
expected = SOUTH_EAST;
assertEquals(expected, MoveTrainPreMove.findNextStep(world, pot,
target));
pot.move(expected);
expected = SOUTH;
assertEquals(expected, MoveTrainPreMove.findNextStep(world, pot,
target));
pot.move(expected);
}
}

AddTrainPreMoveTest

Full name: jfreerails.controller.AddTrainPreMoveTest

Documentation

/**
* Junit test for AddTrainPreMove.
*
* @author Luke
*
*/

Source Code

/**
* Junit test for AddTrainPreMove.
*
* @author Luke
*
*/
public class AddTrainPreMoveTest extends AbstractMoveTestCase {
TrackMoveProducer trackBuilder;
StationBuilder stationBuilder;
FreerailsPrincipal principal;
private ImPoint stationA;
private ImPoint stationB;
ImmutableSchedule defaultSchedule;
@Override
protected void setupWorld() {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
trackBuilder = new TrackMoveProducer(me, world, mr);
stationBuilder = new StationBuilder(me);
// Build track.
stationBuilder
.setStationType(stationBuilder.getTrackTypeID("terminal"));
Step[] track = {EAST, EAST, EAST, EAST, EAST, EAST, EAST, EAST, EAST};
stationA = new ImPoint(10, 10);
MoveStatus ms0 = trackBuilder.buildTrack(stationA, track);
assertTrue(ms0.ok);
// Build 2 stations.
MoveStatus ms1 = stationBuilder.buildStation(stationA);
assertTrue(ms1.ok);
stationB = new ImPoint(19, 10);
MoveStatus ms2 = stationBuilder.buildStation(stationB);
assertTrue(ms2.ok);
TrainOrdersModel order0 = new TrainOrdersModel(0, null, false, false);
TrainOrdersModel order1 = new TrainOrdersModel(1, null, false, false);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
defaultSchedule = s.toImmutableSchedule();
}
@Override
public void testMove() {
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0),
stationA, principal, defaultSchedule);
Move m = preMove.generateMove(world);
assertDoMoveIsOk(m);
assertUndoMoveIsOk(m);
assertSurvivesSerialisation(m);
}
/**
* Check that the path on tiles created for the new train is actually on
* the track.
*/
public void testPathOnTiles() {
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0),
stationA, principal, defaultSchedule);
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.ok);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
TrainMotion motion = ta.findCurrentMotion(0);
assertNotNull(motion);
PathOnTiles path = motion.getTiles(motion.duration());
assertTrackHere(path);
}
public void testMove2() {
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0),
stationA, principal, defaultSchedule);
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.ok);
ActivityIterator ai = world.getActivities(principal, 0);
TrainMotion tm = (TrainMotion) ai.getActivity();
assertEquals(0d, tm.duration());
assertEquals(0d, tm.getSpeedAtEnd());
assertEquals(0d, tm.getDistance(0));
PositionOnTrack pot = tm.getFinalPosition();
assertNotNull(pot);
assertEquals(EAST, pot.facing());
assertEquals(13, pot.getX());
assertEquals(10, pot.getY());
}
public void testGetSchedule() {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
TrackMoveProducer producer = new TrackMoveProducer(me, world, mr);
Step[] trackPath = {EAST, SOUTH_EAST, SOUTH, SOUTH_WEST, WEST,
NORTH_WEST, NORTH, NORTH_EAST};
ImPoint from = new ImPoint(5, 5);
MoveStatus ms = producer.buildTrack(from, trackPath);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
TrainOrdersModel[] orders = {};
ImmutableSchedule is = new ImmutableSchedule(orders, -1, false);
AddTrainPreMove addTrain = new AddTrainPreMove(0, new ImInts(), from,
principal, is);
Move m = addTrain.generateMove(world);
ms = m.doMove(world, principal);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
TrainAccessor ta = new TrainAccessor(world, principal, 0);
assertNotNull(ta.getTarget());
}
public void testInvalidSchedule() {
try {
TrainOrdersModel order0 = new TrainOrdersModel(10, null, false, false);
TrainOrdersModel order1 = new TrainOrdersModel(1, null, false, false);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
ImmutableSchedule invalidSchedule = s.toImmutableSchedule();
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0),
stationA, principal, invalidSchedule);
preMove.generateMove(world);
fail();
} catch (ArrayIndexOutOfBoundsException e) {
}
}
}

TrackBuildingTest

Full name: jfreerails.controller.TrackBuildingTest

Documentation

/**
* <p>
* This test class verifies the functionality of building tracks in a rail simulation environment.
* It includes various test cases to ensure that track construction works correctly under different scenarios,
* including straight lines, single track pieces, terminal handling, double track extensions, and sharp curves.
* </p>
*
* <p>
* The class tests the interaction between the TrackPathFinder, TrackMoveProducer, and BuildTrackStrategy
* to ensure proper pathfinding and track construction logic. It also validates edge cases such as terminal
* interference and double track routing.
* </p>
*
* @author John Doe
* @since 1.0
* @see TrackPathFinder
* @see TrackMoveProducer
* @see BuildTrackStrategy
* @see StationBuilder
*/

Source Code

public class TrackBuildingTest extends TestCase {
World w;
TrackMoveProducer producer;
TrackPathFinder pathFinder;
StationBuilder stationBuilder;
BuildTrackStrategy bts;
@Override
protected void setUp() throws Exception {
super.setUp();
w = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(w, 0);
ModelRoot mr = new ModelRootImpl();
producer = new TrackMoveProducer(me, w, mr);
FreerailsPrincipal principal = w.getPlayer(0).getPrincipal();
pathFinder = new TrackPathFinder(w, principal);
stationBuilder = new StationBuilder(me);
bts = BuildTrackStrategy.getDefault(w);
}
/** Tests building track from 5,5 to 10,5 */
public void testBuildingStraight() {
ImPoint from = new ImPoint(5, 5);
ImPoint to = new ImPoint(10, 5);
try {
// Check there is no track before we build it.
for (int x = 5; x <= 10; x++) {
TrackPiece tp = ((FreerailsTile) w.getTile(x, 5)).getTrackPiece();
assertEquals(NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER, tp
.getTrackTypeID());
}
pathFinder.setupSearch(from, to, bts);
pathFinder.search(-1);
assertEquals(pathFinder.getStatus(),
IncrementalPathFinder.PATH_FOUND);
Step[] path = pathFinder.pathAsVectors();
assertEquals(path.length, 5);
for (int i = 0; i < 5; i++) {
assertEquals(Step.EAST, path[i]);
}
MoveStatus ms = producer.buildTrack(from, path);
assertTrue(ms.message, ms.ok);
// Check track has been built.
for (int x = 5; x <= 10; x++) {
TrackPiece tp = ((FreerailsTile) w.getTile(x, 5)).getTrackPiece();
assertEquals(0, tp.getTrackTypeID());
}
} catch (PathNotFoundException e) {
fail();
}
}
/** Tests building track from 5,5 to 6,5 */
public void testBuildingOneTrackPiece() {
ImPoint from = new ImPoint(5, 5);
ImPoint to = new ImPoint(6, 5);
try {
// Check there is no track before we build it.
TrackPiece tp1 = ((FreerailsTile) w.getTile(5, 5)).getTrackPiece();
assertEquals(NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER, tp1
.getTrackTypeID());
TrackPiece tp2 = ((FreerailsTile) w.getTile(6, 5)).getTrackPiece();
assertEquals(NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER, tp2
.getTrackTypeID());
pathFinder.setupSearch(from, to, bts);
pathFinder.search(-1);
assertEquals(pathFinder.getStatus(),
IncrementalPathFinder.PATH_FOUND);
Step[] path = pathFinder.pathAsVectors();
assertEquals(path.length, 1);
assertEquals(Step.EAST, path[0]);
MoveStatus ms = producer.buildTrack(from, path);
assertTrue(ms.message, ms.ok);
// Check track has been built.
tp1 = ((FreerailsTile) w.getTile(5, 5)).getTrackPiece();
assertEquals(0, tp1.getTrackTypeID());
tp2 = ((FreerailsTile) w.getTile(6, 5)).getTrackPiece();
assertEquals(0, tp2.getTrackTypeID());
} catch (PathNotFoundException e) {
fail();
}
}
/**
* There is a bug where if a section of track has a terminal on the end, you
* cannot extend the track through the terminal. Instead, the track path
* finder finds a route that misses out the terminal.
*
*/
public void testTerminalProblem() {
try {
ImPoint from = new ImPoint(5, 5);
Step[] path = { EAST, EAST, EAST };
MoveStatus ms = producer.buildTrack(from, path);
assertTrue(ms.ok);
int terminalStationType = stationBuilder.getTrackTypeID("terminal");
stationBuilder.setStationType(terminalStationType);
ms = stationBuilder.buildStation(new ImPoint(8, 5));
assertTrue(ms.ok);
pathFinder.setupSearch(new ImPoint(7, 5), new ImPoint(9, 5), bts);
pathFinder.search(-1);
path = pathFinder.pathAsVectors();
assertEquals(2, path.length);
Step[] expectedPath = { EAST, EAST };
assertTrue(Arrays.equals(expectedPath, path));
} catch (PathNotFoundException e) {
fail();
}
}
/**
* There is a bug where if you build a straight section of double track
* going E, then move the cursor to the end and attempt to build more double
* track going SE, the track path finder builds a loop rather than just
* building track going SE
*
*/
public void testDoubleTrackProblem() {
try {
int trackTypeID = stationBuilder.getTrackTypeID("double track");
bts = BuildTrackStrategy.getSingleRuleInstance(trackTypeID, w);
producer.setBuildTrackStrategy(bts);
ImPoint a = new ImPoint(5, 5);
ImPoint b = new ImPoint(6, 5);
ImPoint c = new ImPoint(7, 6);
pathFinder.setupSearch(a, b, bts);
pathFinder.search(-1);
Step[] path = pathFinder.pathAsVectors();
Step[] expectedPath = { EAST };
assertTrue(Arrays.equals(expectedPath, path));
MoveStatus ms = producer.buildTrack(a, path);
assertTrue(ms.ok);
TrackPiece tp = ((FreerailsTile) w.getTile(b.x, b.y)).getTrackPiece();
assertEquals("We just build double track here.", trackTypeID, tp
.getTrackTypeID());
pathFinder.setupSearch(b, c, bts);
pathFinder.search(-1);
path = pathFinder.pathAsVectors();
assertEquals(1, path.length);
expectedPath = new Step[] { SOUTH_EAST };
assertTrue(Arrays.equals(expectedPath, path));
} catch (PathNotFoundException e) {
fail();
}
}
/**
* There is a bug where if you try to start building track on a 90 degree
* bend, no track path is found even when one should exist.
*
*/
public void testStartSearchOnSharpCurve() {
try {
ImPoint from = new ImPoint(5, 5);
Step[] path = { EAST, SOUTH };
MoveStatus ms = producer.buildTrack(from, path);
assertTrue(ms.ok);
pathFinder.setupSearch(new ImPoint(6, 5), new ImPoint(6, 7), bts);
pathFinder.search(-1);
path = pathFinder.pathAsVectors();
assertEquals(2, path.length);
assertEquals(SOUTH, path[0]);
assertEquals(SOUTH, path[1]);
} catch (PathNotFoundException e) {
fail();
}
}
}

TrainStopsHandlerTest

Full name: jfreerails.controller.TrainStopsHandlerTest

Documentation

/**
* Test for
* @author Luke
*/

Source Code

/**
* Test for
* @author Luke
*/
public class TrainStopsHandlerTest {
World w;
public TrainStopsHandlerTest() {
}
@Before
public void setup() throws Exception {
MapCustomizer mc = new MapCustomizer();
ImPoint a = new ImPoint(10, 10);
ImPoint b = new ImPoint(20, 20);
mc.buildTrack(a, b).buildStation(a).buildStation(b);
mc.buildTrain(a, 0, 0);
w = mc.w;
}
/**
A train can have an empty schedule if all stops are removed from the
* schedule or all the stations on the schedule are bulldozed.
*
* See bug #199 Unexpected Exception: null line -1
*/
@Test
public void testWithEmptySchedule() {
FreerailsPrincipal principal = w.getPlayer(0).getPrincipal();
assertEquals(2, w.size(principal, KEY.STATIONS));
assertEquals(1, w.size(principal, KEY.TRAINS));
WorldDiffs diffs = new WorldDiffs(w);
TrainStopsHandler tsh = new TrainStopsHandler(0, principal, diffs);
assertFalse(tsh.isWaiting4FullLoad());
ImmutableSchedule schedule = new MutableSchedule().toImmutableSchedule();
w.set(principal, KEY.TRAIN_SCHEDULES, 0, schedule);
boolean waiting4FullLoad = tsh.isWaiting4FullLoad();
assertFalse(waiting4FullLoad);
}
}

ToAndFroPathIteratorTest

Full name: jfreerails.controller.ToAndFroPathIteratorTest

Documentation

/**
* JUnit test for ToAndFroPathIteratorTest.
*
* @author Luke Lindsay 30-Oct-2002
*
*/

Source Code

/**
* JUnit test for ToAndFroPathIteratorTest.
*
* @author Luke Lindsay 30-Oct-2002
*
*/
public class ToAndFroPathIteratorTest extends TestCase {
public ToAndFroPathIteratorTest(String arg0) {
super(arg0);
}
public void testNextSegment() {
List<Point> l = new ArrayList<Point>();
IntLine line = new IntLine();
l.add(new Point(0, 1));
l.add(new Point(10, 11));
l.add(new Point(20, 22));
FreerailsPathIterator it = new ToAndFroPathIterator(l);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(0, 1, 10, 11, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(10, 11, 20, 22, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(20, 22, 10, 11, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(10, 11, 0, 1, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(0, 1, 10, 11, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(10, 11, 20, 22, line);
}
private void assertLineEquals(int x1, int y1, int x2, int y2, IntLine line) {
assertEquals(x1, line.x1);
assertEquals(x2, line.x2);
assertEquals(y1, line.y1);
assertEquals(y2, line.y2);
}
}

BuildTrackExplorerTest

Full name: jfreerails.controller.BuildTrackExplorerTest

Documentation

/**
* JUnit test for BuildTrackExplorer.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test for BuildTrackExplorer.
*
* @author Luke
*
*/
public class BuildTrackExplorerTest extends TestCase {
private WorldImpl world;
private Player testPlayer = new Player("test", 0);
private FreerailsPrincipal principal;
@Override
protected void setUp() throws Exception {
world = new WorldImpl(20, 20);
world.addPlayer(testPlayer);
world.set(ITEM.GAME_RULES, GameRules.NO_RESTRICTIONS);
principal = testPlayer.getPrincipal();
MapFixtureFactory.generateTrackRuleList(world);
}
/**
* On a blank map, we should be able to build track in any direction as long
* as it does not go off the map.
*/
public void test1() {
PositionOnTrack start;
// Test starting in the middle of the map.
start = PositionOnTrack.createComingFrom(10, 10, Step.NORTH);
BuildTrackExplorer explorer = new BuildTrackExplorer(world, principal);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.NORTH, 10, 9, explorer);
assertNextVertexIs(Step.NORTH_EAST, 11, 9, explorer);
assertNextVertexIs(Step.EAST, 11, 10, explorer);
// We miss out SW, S, and SE since we don't want to double back on
// ourselves.
assertNextVertexIs(Step.WEST, 9, 10, explorer);
assertNextVertexIs(Step.NORTH_WEST, 9, 9, explorer);
assertFalse(explorer.hasNextEdge());
// Test starting in the top left of the map.
start = PositionOnTrack.createComingFrom(0, 0, Step.SOUTH_EAST);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.EAST, 1, 0, explorer);
assertNextVertexIs(Step.SOUTH_EAST, 1, 1, explorer);
assertNextVertexIs(Step.SOUTH, 0, 1, explorer);
assertFalse(explorer.hasNextEdge());
// Test starting in the bottom right of the map.
start = PositionOnTrack.createComingFrom(19, 19, Step.NORTH_WEST);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.NORTH, 19, 18, explorer);
assertNextVertexIs(Step.WEST, 18, 19, explorer);
assertNextVertexIs(Step.NORTH_WEST, 18, 18, explorer);
assertFalse(explorer.hasNextEdge());
}
/** Test when we cannot build on some terrain types. */
public void test2() {
// Check the the Ocean type is where we think it is.
int oceanTypeNumber = 4;
TileTypeImpl ocean = (TileTypeImpl) world.get(SKEY.TERRAIN_TYPES,
oceanTypeNumber);
assertEquals(TerrainType.Category.Ocean, ocean.getCategory());
// Check that track cannot be built on ocean.
for (int i = 0; i < world.size(SKEY.TRACK_RULES); i++) {
TrackRule rule = (TrackRule) world.get(SKEY.TRACK_RULES, i);
assertFalse(rule.canBuildOnThisTerrainType(ocean.getCategory()));
}
// Place some ocean.
FreerailsTile tile = FreerailsTile.getInstance(oceanTypeNumber);
world.setTile(10, 9, tile);
world.setTile(11, 10, tile);
PositionOnTrack start;
// Test starting in the middle of the map.
start = PositionOnTrack.createComingFrom(10, 10, Step.NORTH);
BuildTrackExplorer explorer = new BuildTrackExplorer(world, principal);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.NORTH_EAST, 11, 9, explorer);
// We miss out SW, S, and SE since we don't want to double back on
// ourselves.
assertNextVertexIs(Step.WEST, 9, 10, explorer);
assertNextVertexIs(Step.NORTH_WEST, 9, 9, explorer);
assertFalse(explorer.hasNextEdge());
}
/** Test for illegal track configurations. */
public void test3() {
// Build some track, from 10, 10 diagonally SE.
int y = 10;
int x = 10;
for (int i = 0; i < 4; i++) {
Step v = Step.SOUTH_EAST;
buildTrack(x, y, v);
x += v.deltaX;
y += v.deltaY;
}
// If we enter 10, 10 from the south, we should be able to build track S
// & SW.
PositionOnTrack start = PositionOnTrack.createComingFrom(10, 10,
Step.SOUTH);
BuildTrackExplorer explorer = new BuildTrackExplorer(world, principal);
explorer.setPosition(start.toInt());
// SE is going along existing track
assertNextVertexIs(Step.SOUTH_EAST, 11, 11, explorer);
// S is building new track.
assertNextVertexIs(Step.SOUTH, 10, 11, explorer);
assertFalse(explorer.hasNextEdge());
// If we enter 10, 11 from the north, we should be able to build track
// N, E, W, & NW.
start = PositionOnTrack.createComingFrom(10, 11, Step.NORTH);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.NORTH, 10, 10, explorer);
assertNextVertexIs(Step.EAST, 11, 11, explorer);
assertNextVertexIs(Step.WEST, 9, 11, explorer);
assertNextVertexIs(Step.NORTH_WEST, 9, 10, explorer);
assertFalse(explorer.hasNextEdge());
// If we enter 10, 12 from the north, we also should be able to build
// track N, E, W, & NW.
start = PositionOnTrack.createComingFrom(10, 12, Step.NORTH);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.NORTH, 10, 11, explorer);
assertNextVertexIs(Step.EAST, 11, 12, explorer);
assertNextVertexIs(Step.WEST, 9, 12, explorer);
assertNextVertexIs(Step.NORTH_WEST, 9, 11, explorer);
assertFalse(explorer.hasNextEdge());
}
private void assertNextVertexIs(Step oneTileMoveVector, int x, int y,
BuildTrackExplorer explorer) {
assertTrue(explorer.hasNextEdge());
explorer.nextEdge();
PositionOnTrack pos = new PositionOnTrack(explorer
.getVertexConnectedByEdge());
assertEquals(PositionOnTrack.createComingFrom(x, y, oneTileMoveVector),
pos);
}
private void buildTrack(int x, int y, Step direction) {
TrackRule rule = (TrackRule) world.get(SKEY.TRACK_RULES, 0);
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(new ImPoint(x, y), direction, rule,
rule, world, MapFixtureFactory.TEST_PRINCIPAL);
MoveStatus ms = move.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.ok);
}
}

MoveTrainPreMove3rdTest

Full name: jfreerails.controller.MoveTrainPreMove3rdTest

Documentation

/** Unit test for MoveTrainPreMove, tests pathfinding.*/

Source Code

/** Unit test for MoveTrainPreMove, tests pathfinding.*/
public class MoveTrainPreMove3rdTest extends TestCase {
TrackMoveProducer trackBuilder;
StationBuilder stationBuilder;
FreerailsPrincipal principal;
private ImPoint stationA;
World world;
Step[] line1 = { EAST, NORTH_EAST, EAST, NORTH_EAST, NORTH};
Step[] line2 = { WEST, WEST, SOUTH_WEST, SOUTH, SOUTH_EAST, EAST};
Step[] line3 = { NORTH_WEST, NORTH_WEST, NORTH, NORTH, NORTH_EAST};
@Override
protected void setUp() throws Exception {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
trackBuilder = new TrackMoveProducer(me, world, mr);
stationBuilder = new StationBuilder(me);
// Build track.
stationBuilder
.setStationType(stationBuilder.getTrackTypeID("terminal"));
stationA = new ImPoint(10, 10);
MoveStatus ms0 = trackBuilder.buildTrack(stationA, line1);
assertTrue(ms0.ok);
ms0 = trackBuilder.buildTrack(stationA, line2);
assertTrue(ms0.ok);
ms0 = trackBuilder.buildTrack(stationA, line3);
assertTrue(ms0.ok);
}
public void testFindingPath(){
findPath2Target(new ImPoint(14, 7), line1);
findPath2Target(new ImPoint(9, 13), line2);
findPath2Target(new ImPoint(9, 13), line2);
}
private void findPath2Target(ImPoint target1, Step[] expectedPath) {
FreerailsTile tile = (FreerailsTile)world.getTile(target1.x, target1.y);
assertTrue(tile.hasTrack());
PositionOnTrack pot = PositionOnTrack.createFacing(10, 10, EAST);
for (int i = 0; i < expectedPath.length; i++) {
Step expected = expectedPath[i];
Step actual = MoveTrainPreMove.findNextStep(world,pot, target1);
assertEquals(String.valueOf(i), expected, actual);
pot.move(expected);
}
}
}

FlatTrackExplorerTest

Full name: jfreerails.controller.FlatTrackExplorerTest

Documentation

/**
* JUnit test for FlatTrackExplorer.
*
* 24-Nov-2002
*
* @author Luke Lindsay
*
*/

Source Code

/**
* JUnit test for FlatTrackExplorer.
*
* 24-Nov-2002
*
* @author Luke Lindsay
*
*/
public class FlatTrackExplorerTest extends TestCase {
private WorldImpl world;
public FlatTrackExplorerTest(String arg0) {
super(arg0);
}
private Player testPlayer = new Player("test", 0);
@Override
protected void setUp() {
world = new WorldImpl(20, 20);
world.addPlayer(testPlayer);
world.set(ITEM.GAME_RULES, GameRules.NO_RESTRICTIONS);
MapFixtureFactory.generateTrackRuleList(world);
TrackRule rule = (TrackRule) world.get(SKEY.TRACK_RULES, 0);
Step[] vectors = { Step.WEST, Step.EAST, Step.NORTH_EAST };
ImPoint p = new ImPoint(10, 10);
ImPoint[] points = { p, p, p };
for (int i = 0; i < points.length; i++) {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(points[i], vectors[i], rule, rule,
world, MapFixtureFactory.TEST_PRINCIPAL);
MoveStatus ms = move.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.ok);
}
}
public void testGetFirstVectorToTry() {
setUp();
PositionOnTrack p = PositionOnTrack.createComingFrom(10, 10,
Step.SOUTH_WEST);
FlatTrackExplorer fte = new FlatTrackExplorer(world, p);
Step v = fte.getFirstVectorToTry();
assertEquals(Step.EAST, v);
}
/**
* Tests that the track explorer at point 10,10 tells us that we can move
* west, east, or northeast.
*/
public void testGetPossibleDirections() {
setUp();
FlatTrackExplorer fte;
PositionOnTrack p = PositionOnTrack.createComingFrom(10, 10,
Step.SOUTH_WEST);
fte = new FlatTrackExplorer(world, p);
// There should be 3 branches.
assertTrue(fte.hasNextEdge());
fte.nextEdge();
p.setValuesFromInt(fte.getVertexConnectedByEdge());
assertEquals(Step.EAST, p.cameFrom());
assertTrue(fte.hasNextEdge());
fte.nextEdge();
p.setValuesFromInt(fte.getVertexConnectedByEdge());
assertEquals(Step.WEST, p.cameFrom());
assertTrue(fte.hasNextEdge());
fte.nextEdge();
p.setValuesFromInt(fte.getVertexConnectedByEdge());
assertEquals(Step.NORTH_EAST, p.cameFrom());
assertTrue(!fte.hasNextEdge());
}
/**
* Tests that we can move the track explorer at point 10,10 northeast, and
* that when we have done this, we can move it back again.
*/
public void testMoveTrackExplorer() {
setUp();
FlatTrackExplorer fte;
PositionOnTrack p = PositionOnTrack.createComingFrom(10, 10, Step.EAST);
fte = new FlatTrackExplorer(world, p);
PositionOnTrack pos = new PositionOnTrack(fte.getPosition());
assertEquals(10, pos.getX());
assertEquals(10, pos.getY());
assertTrue(fte.hasNextEdge());
fte.nextEdge();
pos.setValuesFromInt(fte.getVertexConnectedByEdge());
assertEquals(Step.NORTH_EAST, pos.cameFrom());
assertEquals(11, pos.getX());
assertEquals(9, pos.getY());
int branchPosition = fte.getVertexConnectedByEdge();
fte.moveForward();
assertEquals(branchPosition, fte.getPosition());
pos.setValuesFromInt(fte.getPosition());
assertEquals(11, pos.getX());
assertEquals(9, pos.getY());
assertTrue(fte.hasNextEdge());
fte.nextEdge();
assertEquals(Step.SOUTH_WEST, fte.currentBranch.cameFrom());
assertTrue(!fte.hasNextEdge());
fte.moveForward();
pos.setValuesFromInt(fte.getPosition());
assertEquals(10, pos.getX());
assertEquals(10, pos.getY());
}
public void testHasNext() {
setUp();
FlatTrackExplorer explorer = new FlatTrackExplorer(world,
PositionOnTrack.createComingFrom(10, 10, Step.EAST));
assertTrue(explorer.hasNextEdge());
}
public void testGetPossiblePositions() {
setUp();
PositionOnTrack[] positions = FlatTrackExplorer.getPossiblePositions(
world, new ImPoint(10, 10));
assertNotNull(positions);
assertEquals(3, positions.length);
HashSet<Step> directions = new HashSet<Step>();
directions.add(Step.WEST);
directions.add(Step.EAST);
directions.add(Step.SOUTH_WEST);
HashSet<Step> directions2 = new HashSet<Step>();
for (int i = 0; i < positions.length; i++) {
directions2.add(positions[i].cameFrom());
}
assertEquals(directions, directions2);
}
}

MoveTrainPreMove2ndTest

Full name: jfreerails.controller.MoveTrainPreMove2ndTest

Documentation

/** Unit test for MoveTrainPreMove, tests stopping at stations. */

Source Code

/** Unit test for MoveTrainPreMove, tests stopping at stations. */
public class MoveTrainPreMove2ndTest extends AbstractMoveTestCase {
TrackMoveProducer trackBuilder;
StationBuilder stationBuilder;
FreerailsPrincipal principal;
private ImPoint station0Location;
private ImPoint station1Location;
private ImPoint station2Location;
ImmutableSchedule defaultSchedule;
@Override
/** <ol>
* <li>Obtains a map from MapFixtureFactory2</li>
* <li>Builds a track from (10,10) to (30, 10).</li>
* <li>Builds stations at (10,10), (20, 10), and (28,10).</li>
* <li>Builds a train with two wagons of type #0 and places it at (10, 10)</li>
* <li>Schedules the train to move between stations 0 and 2 without changing consist</li>
* </ol>
*/
protected void setUp() throws Exception {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
trackBuilder = new TrackMoveProducer(me, world, mr);
stationBuilder = new StationBuilder(me);
// Build track.
stationBuilder.setStationType(stationBuilder.getTrackTypeID("terminal"));
Step[] track = new Step[20];
for (int i = 0; i < track.length; i++) {
track[i] = EAST;
}
station0Location = new ImPoint(10, 10);
MoveStatus ms0 = trackBuilder.buildTrack(station0Location, track);
assertTrue(ms0.ok);
// Build 2 stations.
MoveStatus ms1 = stationBuilder.buildStation(station0Location);
assertTrue(ms1.ok);
station1Location = new ImPoint(20, 10);
MoveStatus ms2 = stationBuilder.buildStation(station1Location);
assertTrue(ms2.ok);
station2Location = new ImPoint(28, 10);
MoveStatus ms3 = stationBuilder.buildStation(station2Location);
assertTrue(ms3.ok);
TrainOrdersModel order0 = new TrainOrdersModel(2, null, false, false);
TrainOrdersModel order1 = new TrainOrdersModel(0, null, false, false);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
defaultSchedule = s.toImmutableSchedule();
ImPoint start = new ImPoint(10, 10);
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0), start, principal,
defaultSchedule);
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, principal);
assertTrue(ms.ok);
}
public void testPathFinding() {
// setTargetAsStation2();
Step step = nextStep();
assertEquals(EAST, step);
moveTrain();
assertEquals(EAST, nextStep());
moveTrain();
assertEquals(EAST, nextStep());
}
private Step nextStep() {
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
Step step = preMove.nextStep(world);
return step;
}
/** Test that when the train arrives at a non station tile it keeps moving. */
public void testStops1() {
for (int i = 0; i < 5; i++) {
TrainMotion tm = moveTrain();
PositionOnTrack pot = tm.getFinalPosition();
assertEquals(14 + i, pot.getX());
assertEquals(READY, tm.getActivity());
assertTrue(tm.getSpeedAtEnd() > 0);
}
}
private TrainMotion moveTrain() {
incrTime(world, principal);
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, principal);
assertTrue(ms.message, ms.ok);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
TrainMotion tm = ta.findCurrentMotion(Integer.MAX_VALUE);
return tm;
}
/**
* Test that when the train arrives at a non scheduled station tile it stops,
* drops off and picks up cargo, then continues
*/
public void testStops2() {
// Check that there two stations on the schedule: station0 and station2;
TrainAccessor ta = new TrainAccessor(world, principal, 0);
ImmutableSchedule schedule = ta.getSchedule();
assertEquals(2, schedule.getNumOrders());
assertEquals(2, schedule.getOrder(0).getStationID());
// Check the train should have 2 wagons for cargo #0
ImInts expectedConsist = new ImInts(0, 0);
ImInts actualConsist = ta.getTrain().getConsist();
assertEquals(expectedConsist, actualConsist);
addCargoAtStation(1, 800);
// Move the train to just before station 1.
PositionOnTrack pot;
TrainMotion tm;
do {
tm = moveTrain();
pot = tm.getFinalPosition();
} while (pot.getX() < station1Location.x);
assertEquals(station1Location.x, pot.getX());
assertEquals(station1Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
// The next train motion should represent the stop at the station.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station1Location.x, pot.getX());
assertEquals(station1Location.y, pot.getY());
assertEquals(STOPPED_AT_STATION, tm.getActivity());
// 80 Units of cargo should have been transferred to the train!
CargoBundle onTrain = ta.getCargoBundle();
int amount = onTrain.getAmount(0);
assertEquals(80, amount);
// Then the train should continue.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station1Location.x + 1, pot.getX());
assertEquals(station1Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
}
/** Adds the specified amount of cargo #0 to the specified station. */
private void addCargoAtStation(int stationId, int amount) {
CargoBatch cb = new CargoBatch(0, 6, 6, 0, stationId);
MutableCargoBundle mb = new MutableCargoBundle();
mb.addCargo(cb, amount);
StationModel station1Model = (StationModel) world.get(principal, KEY.STATIONS, stationId);
ImmutableCargoBundle cargoAtStationBefore = mb.toImmutableCargoBundle();
int station1BundleId = station1Model.getCargoBundleID();
world.set(principal, KEY.CARGO_BUNDLES, station1BundleId, cargoAtStationBefore);
}
/**
* Test that when the train arrives at a scheduled station tile it stops,
* updates its schedule and transfers cargo and starts moving again.
*/
public void testStops3() {
// Add cargo to station 2
addCargoAtStation(2, 800);
// Keep moving train until it reaches station 2
PositionOnTrack pot;
TrainMotion tm;
int x;
do {
tm = moveTrain();
pot = tm.getFinalPosition();
x = pot.getX();
} while (x < station2Location.x);
assertEquals(station2Location.x, x);
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
// The train should be heading for station 1.
TrainAccessor ta = new TrainAccessor(world, principal, 0);
Schedule schedule1 = ta.getSchedule();
assertEquals(0, schedule1.getOrderToGoto());
assertEquals(2, schedule1.getStationToGoto());
ImPoint expectedTarget = new ImPoint(station2Location.x, station2Location.y);
assertEquals(expectedTarget, ta.getTarget());
// The next train motion should represent the stop at the station.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station2Location.x, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(STOPPED_AT_STATION, tm.getActivity());
// The train should be heading for station 0.
Schedule schedule2 = ta.getSchedule();
assertFalse(schedule2.equals(schedule1));
assertEquals(1, schedule2.getOrderToGoto());
assertEquals(0, schedule2.getStationToGoto());
// 80 Units of cargo should have been transferred to the train!
CargoBundle onTrain = ta.getCargoBundle();
int amount = onTrain.getAmount(0);
assertEquals(80, amount);
// Then the train should continue.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station2Location.x - 1, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
}
/**
* Test that when the train <b>is</b> scheduled to wait for full load, it
* waits.
*/
public void testStops5() {
PositionOnTrack pot;
TrainMotion tm;
putTrainAtStationWaiting4FullLoad();
// Add enough cargo to fill up the train.
addCargoAtStation(2, 70);
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station2Location.x - 1, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
}
private void putTrainAtStationWaiting4FullLoad() {
// Set wait until full on schedule.
ImInts newConsist = new ImInts(0, 0);
TrainOrdersModel order0 = new TrainOrdersModel(2, newConsist, true, false);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
MutableSchedule schedule = new MutableSchedule(ta.getSchedule());
schedule.setOrder(0, order0);
ImmutableSchedule imSchedule = schedule.toImmutableSchedule();
world.set(principal, KEY.TRAIN_SCHEDULES, 0, imSchedule);
assertEquals(0, ta.getSchedule().getOrderToGoto());
assertTrue(ta.getSchedule().getOrder(0).waitUntilFull);
// Add some cargo to station #2, but not enough to fill the train.
addCargoAtStation(2, 20);
// Move the train to just before station 2.
PositionOnTrack pot;
TrainMotion tm;
do {
tm = moveTrain();
pot = tm.getFinalPosition();
} while (pot.getX() < station2Location.x);
assertEquals(station2Location.x, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
// The train should now stop at the station
// and wait for a full load.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station2Location.y, pot.getY());
assertEquals(WAITING_FOR_FULL_LOAD, tm.getActivity());
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
assertFalse("The train isn't full and there is no cargo to add, so we should be able to generate a move.", preMove.isUpdateDue(world));
}
/** Test that a waiting train whose orders change behaves correctly. */
public void testStops6() {
PositionOnTrack pot;
TrainMotion tm;
putTrainAtStationWaiting4FullLoad();
// Now change the train's orders.
ImInts newConsist = new ImInts(0, 0);
TrainOrdersModel order0 = new TrainOrdersModel(2, newConsist, false, false);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
MutableSchedule schedule = new MutableSchedule(ta.getSchedule());
schedule.setOrder(0, order0);
ImmutableSchedule imSchedule = schedule.toImmutableSchedule();
world.set(principal, KEY.TRAIN_SCHEDULES, 0, imSchedule);
assertEquals(0, ta.getSchedule().getOrderToGoto());
assertFalse(ta.getSchedule().getOrder(0).waitUntilFull);
// Then the train should continue.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station2Location.x - 1, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
}
/** Tests that a train with 'select wagons automatically' enable behaves correctly.*/
public void ignoreTestAutoConsist(){
TrainAccessor ta = new TrainAccessor(world, principal, 0);
//Remove all wagons from the train.
TrainModel model = ta.getTrain();
model = model.getNewInstance(model.getEngineType(), new ImInts());
world.set(principal, KEY.TRAINS, 0, model);
//Change trains schedule to auto consist.
TrainOrdersModel order0 = new TrainOrdersModel(1, null, false, true);
TrainOrdersModel order1 = new TrainOrdersModel(2, null, false, true);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
world.set(principal, KEY.TRAIN_SCHEDULES, 0, s.toImmutableSchedule());
assertEquals(0, ta.getSchedule().getOrderToGoto());
//Add 35 unit of cargo #0 to station 1.
StationModel station0 = (StationModel)world.get(principal, KEY.STATIONS, 1);
int cargoBundleId = station0.getCargoBundleID();
MutableCargoBundle mcb = new MutableCargoBundle();
final int AMOUNT_OF_CARGO = 35;
mcb.addCargo(new CargoBatch(0, 0,0, 0, 0), AMOUNT_OF_CARGO);
world.set(principal, KEY.CARGO_BUNDLES, cargoBundleId, mcb.toImmutableCargoBundle());
//Make station2 demand cargo #0;
boolean[] boolArray = new boolean[world.size(SKEY.CARGO_TYPES)];
boolArray[0] = true;
Demand4Cargo demand = new Demand4Cargo(boolArray);
StationModel station2 = (StationModel)world.get(principal, KEY.STATIONS, 2);
StationModel stationWithNewDemand = new StationModel(station2, demand);
world.set(principal, KEY.STATIONS, 2, stationWithNewDemand);
//The train should be bound for station 1.
assertEquals(1, ta.getSchedule().getStationToGoto());
//Make train call at station 1.
PositionOnTrack pot;
TrainMotion tm;
do {
tm = moveTrain();
pot = tm.getFinalPosition();
} while (pot.getX() < station1Location.x);
assertEquals(station1Location.x, pot.getX());
assertEquals(station1Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
tm = moveTrain();
pot = tm.getFinalPosition();
//The train should be bound for station 2.
assertEquals(2, ta.getSchedule().getStationToGoto());
//Check that the train has picked up the cargo.
//The train should have one wagon of type #0
assertEquals(new ImInts(0), ta.getTrain().getConsist());
assertEquals(AMOUNT_OF_CARGO, ta.getCargoBundle().getAmount(0));
}
public void testCanGenerateMove() {
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
assertTrue(preMove.isUpdateDue(world));
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, principal);
assertTrue(ms.message, ms.ok);
assertFalse(preMove.isUpdateDue(world));
}
static void incrTime(World w, FreerailsPrincipal p) {
ActivityIterator ai = w.getActivities(p, 0);
while (ai.hasNext())
ai.nextActivity();
double finishTime = ai.getFinishTime();
GameTime newTime = new GameTime((int) Math.floor(finishTime));
w.setTime(newTime);
}
/**
* Tests that when extra wagons are added, the TrainMotion lengthens to
* accommodate them.
*/
public void testLengtheningTrain() {
// Set the train to add wagons at station2.
ImInts newConsist = new ImInts(0, 0, 0, 0, 0, 0);
TrainOrdersModel order0 = new TrainOrdersModel(2, newConsist, false, false);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
MutableSchedule schedule = new MutableSchedule(ta.getSchedule());
schedule.setOrder(0, order0);
ImmutableSchedule imSchedule = schedule.toImmutableSchedule();
world.set(principal, KEY.TRAIN_SCHEDULES, 0, imSchedule);
assertEquals(0, ta.getSchedule().getOrderToGoto());
// Move the train to the station.
PositionOnTrack pot;
TrainMotion tm;
do {
tm = moveTrain();
pot = tm.getFinalPosition();
} while (pot.getX() < station2Location.x);
assertEquals(station2Location.x, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
TrainModel train = ta.getTrain();
assertEquals(2, train.getNumberOfWagons());
assertTrue(tm.getInitialPosition() >= train.getLength());
tm = moveTrain();
tm = moveTrain();
train = ta.getTrain();
assertEquals(6, ta.getTrain().getNumberOfWagons());
assertTrue(tm.getInitialPosition() >= train.getLength());
}
}

StationBuilderTest

Full name: jfreerails.controller.StationBuilderTest

Documentation

/**
* A Junit test.
*
* @author Luke Lindsay
*
*
*/

Source Code

/**
* A Junit test.
*
* @author Luke Lindsay
*
*
*/
public class StationBuilderTest extends TestCase {
World w;
TrackMoveProducer trackBuilder;
StationBuilder stationBuilder;
@Override
protected void setUp() throws Exception {
super.setUp();
w = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(w, 0);
ModelRoot mr = new ModelRootImpl();
trackBuilder = new TrackMoveProducer(me, w, mr);
stationBuilder = new StationBuilder(me);
}
public void testCanBuiltStationHere() {
}
public void testBuildStation() {
stationBuilder
.setStationType(stationBuilder.getTrackTypeID("terminal"));
Step[] track = { EAST, EAST, EAST };
MoveStatus ms = trackBuilder.buildTrack(new ImPoint(10, 10), track);
assertTrue(ms.ok);
assertTrue(stationBuilder.tryBuildingStation(new ImPoint(10, 10)).ok);
assertTrue(stationBuilder.tryBuildingStation(new ImPoint(13, 10)).ok);
MoveStatus ms1 = stationBuilder.buildStation(new ImPoint(10, 10));
assertTrue(ms1.ok);
MoveStatus ms2 = stationBuilder.buildStation(new ImPoint(13, 10));
assertFalse(ms2.ok);
}
}

SimpleAStarPathFinderTest

Full name: jfreerails.controller.SimpleAStarPathFinderTest

Documentation

/**
* JUnit test for SimpleAStarPathFinder. 27-Nov-2002
*
* @author Luke Lindsay
*
*/

Source Code

/**
* JUnit test for SimpleAStarPathFinder. 27-Nov-2002
*
* @author Luke Lindsay
*
*/
public class SimpleAStarPathFinderTest extends TestCase {
private Map map;
private SimpleAStarPathFinder pathFinder;
/**
* Constructor for SimpleAStarPathFinderTest.
*
* @param arg0
*/
public SimpleAStarPathFinderTest(String arg0) {
super(arg0);
}
@Override
protected void setUp() {
this.map = new Map();
pathFinder = new SimpleAStarPathFinder();
}
public void testFindpath() {
setUp();
int i = pathFinder.findstep(0, new int[] { 1 }, map);
assertEquals(1, i);
i = pathFinder.findstep(0, new int[] { 5 }, map);
assertEquals(1, i);
i = pathFinder.findstep(0, new int[] { 4 }, map);
assertEquals(1, i);
i = pathFinder.findstep(5, new int[] { 7 }, map);
assertEquals(6, i);
i = pathFinder.findstep(4, new int[] { 1 }, map);
assertEquals(2, i);
i = pathFinder.findstep(5, new int[] { 0, 7 }, map);
assertEquals(6, i);
i = pathFinder.findstep(5, new int[] { 4 }, map);
assertEquals(2, i);
i = pathFinder.findstep(4, new int[] { 4 }, map);
assertEquals(IncrementalPathFinder.PATH_NOT_FOUND, i);
i = pathFinder.findstep(2, new int[] { 1 }, map);
assertEquals(1, i);
}
public void testExplorer() {
setUp();
assertEquals(0, map.getPosition());
assertTrue(map.hasNextEdge());
map.nextEdge();
assertTrue(!map.hasNextEdge());
assertEquals(1, map.getVertexConnectedByEdge());
assertEquals(11, map.getEdgeCost());
map.moveForward();
assertEquals(1, map.getPosition());
assertTrue(map.hasNextEdge());
map.nextEdge();
assertEquals(0, map.getVertexConnectedByEdge());
// now try jumping to a different position.
map.setPosition(2);
assertEquals(2, map.getPosition());
assertTrue(map.hasNextEdge());
map.nextEdge();
assertEquals(5, map.getVertexConnectedByEdge());
}
}

Node

Full name: jfreerails.controller.Node

Documentation

/**
* Represents a node in a graph structure, containing arrays of edges and distances.
* This class ensures that the edges and distances arrays are of equal length upon construction.
*
* @author YourName
* @since 1.0
*
* @see Graph
*/

Source Code

class Node {
int[] edges;
int[] distances;
Node(int[] e, int[] d) {
if (e.length != d.length) {
throw new IllegalArgumentException("e.length=" + e.length
+ ", e.length=" + e.length);
}
edges = e;
distances = d;
}
}

Methods

Map

Full name: jfreerails.controller.Map

Documentation

/**
* Represents a graph structure for pathfinding, specifically designed for use with A* algorithms.
* This class provides methods to navigate through nodes and edges, allowing traversal and cost evaluation.
*
* @author Your Name
* @see GraphExplorer
* @see Node
*/

Source Code

class Map implements GraphExplorer {
// Look at SimpleAStarPathFinderTest.svg to see it
private final Node[] nodes = new Node[] {
new Node(new int[] { 1 }, new int[] { 11 }), // 0
new Node(new int[] { 0, 5, 2 }, new int[] { 11, 4, 8 }), // 1 //
// try
// {11,4,4}
new Node(new int[] { 5, 3, 4, 1 }, new int[] { 5, 10, 12, 8 }), // 2
// //try{5,10,12,4}
new Node(new int[] { 2 }, new int[] { 10 }), // 3
new Node(new int[] { 5, 2 }, new int[] { 18, 12 }), // 4
new Node(new int[] { 1, 6, 4, 2 }, new int[] { 4, 3, 18, 5 }), // 5
new Node(new int[] { 5, 7 }, new int[] { 3, 4 }), // 6
new Node(new int[] { 6 }, new int[] { 4 }), // 7
};
private int position = 0;
private int branch = -1;
public void setPosition(int i) {
this.position = i;
this.branch = -1;
}
public int getPosition() {
return this.position;
}
public void nextEdge() {
if (hasNextEdge()) {
branch++;
} else {
throw new NoSuchElementException();
}
}
public int getVertexConnectedByEdge() {
return nodes[position].edges[branch];
}
public int getEdgeCost() {
return nodes[position].distances[branch];
}
public boolean hasNextEdge() {
if (nodes[position].edges.length > (branch + 1)) {
return true;
}
return false;
}
public void moveForward() {
this.setPosition(this.getVertexConnectedByEdge());
}
public int getH() {
// TODO Auto-generated method stub
return 0;
}
}

DropOffAndPickupCargoMoveGeneratorTest

Full name: jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest

Documentation

/**
* This Junit TestCase tests whether a train picks up and drops off the right
* cargo at a station.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* This Junit TestCase tests whether a train picks up and drops off the right
* cargo at a station.
*
* @author Luke Lindsay
*
*/
public class DropOffAndPickupCargoMoveGeneratorTest extends TestCase {
private World w;
private final CargoBatch cargoType0FromStation2 = new CargoBatch(0, 0, 0,
0, 2);
private final CargoBatch cargoType1FromStation2 = new CargoBatch(1, 0, 0,
0, 2);
private final CargoBatch cargoType0FromStation0 = new CargoBatch(0, 0, 0,
0, 0);
@Override
protected void setUp() throws Exception {
// Set up the world object with three cargo types, one station, and one
// train.
w = new WorldImpl();
w.addPlayer(MapFixtureFactory.TEST_PLAYER);
// set up the cargo types.
w.add(SKEY.CARGO_TYPES, new CargoType(0, "Mail", Categories.Mail));
w.add(SKEY.CARGO_TYPES, new CargoType(0, "Passengers",
Categories.Passengers));
w.add(SKEY.CARGO_TYPES, new CargoType(0, "Goods",
Categories.Fast_Freight));
// Set up station
int x = 10;
int y = 10;
int stationCargoBundleId = w.add(MapFixtureFactory.TEST_PRINCIPAL,
KEY.CARGO_BUNDLES,
ImmutableCargoBundle.EMPTY_BUNDLE);
String stationName = "Station 1";
StationModel station = new StationModel(x, y, stationName, w
.size(SKEY.CARGO_TYPES), stationCargoBundleId);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, station);
// Set up train
int trainCargoBundleId = w.add(MapFixtureFactory.TEST_PRINCIPAL,
KEY.CARGO_BUNDLES,
ImmutableCargoBundle.EMPTY_BUNDLE);
// 3 wagons to carry cargo type 0.
ImInts wagons = new ImInts(0, 0, 0);
TrainModel train = new TrainModel(wagons, trainCargoBundleId);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.TRAINS, train);
}
/** Tests picking up cargo from a station. */
public void testPickUpCargo1() {
// Set up the variables for this test.
MutableCargoBundle cargoBundleWith2CarloadsOfCargo0 = new MutableCargoBundle();
// cargoBundleWith2CarloadsOfCargo0.setAmount(cargoType0FromStation2,
// 2);
cargoBundleWith2CarloadsOfCargo0.setAmount(cargoType0FromStation2, 80);
assertEquals("There shouldn't be any cargo at the station yet",
ImmutableCargoBundle.EMPTY_BUNDLE, getCargoAtStation());
assertEquals("There shouldn't be any cargo on the train yet",
ImmutableCargoBundle.EMPTY_BUNDLE, getCargoOnTrain());
// Now add 2 carloads of cargo type 0 to the station.
// getCargoAtStation().setAmount(cargoType0FromStation2, 2);
setCargoAtStation(cargoType0FromStation2, 80);
// The train should pick up this cargo, since it has three wagons
// capable of carrying cargo type 0.
stopAtStation();
// The train should now have the two car loads of cargo and there should
// be no cargo at the station.
assertEquals("There should no longer be any cargo at the station",
ImmutableCargoBundle.EMPTY_BUNDLE, getCargoAtStation());
assertEquals("The train should now have the two car loads of cargo",
cargoBundleWith2CarloadsOfCargo0.toImmutableCargoBundle(),
getCargoOnTrain());
}
/**
* Tests picking up cargo when the there is too much cargo at the station
* for the train to carry.
*/
public void testPickUpCargo2() {
setCargoAtStation(this.cargoType0FromStation2, 200);
stopAtStation();
// The train has 3 wagons, each wagon carries 40 units of cargo, so
// the train should pickup 120 units of cargo.
MutableCargoBundle expectedOnTrain = new MutableCargoBundle();
expectedOnTrain.setAmount(this.cargoType0FromStation2, 120);
// The remaining 80 units of cargo should be left at the station.
MutableCargoBundle expectedAtStation = new MutableCargoBundle();
expectedAtStation.setAmount(this.cargoType0FromStation2, 80);
// Test the expected values against the actuals..
assertEquals(expectedOnTrain.toImmutableCargoBundle(),
getCargoOnTrain());
assertEquals(expectedAtStation.toImmutableCargoBundle(),
getCargoAtStation());
}
/**
* Tests that a train takes into account how much cargo it already has and
* the type of wagons it has when it is picking up cargo.
*/
public void testPickUpCargo3() {
ImInts wagons = new ImInts(0, 0, 2, 2);
// 2 wagons for cargo type 0; 2 wagons for cargo type 2.
addWagons(wagons);
// Set cargo on train.
setCargoOnTrain(this.cargoType0FromStation2, 30);
// Set cargo at station.
setCargoAtStation(this.cargoType0FromStation0, 110);
// Check that station does not demand cargo type 0.
StationModel station = (StationModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
0);
assertFalse(station.getDemand().isCargoDemanded(0));
// Stop at station.
stopAtStation();
/*
* The train has 2 wagons for cargo type 0 but had 30 units of cargo
* type 0 before stopping so it can only pick up 50 units.
*/
MutableCargoBundle expectedAtStation = new MutableCargoBundle();
expectedAtStation.setAmount(cargoType0FromStation0, 60);
MutableCargoBundle expectedOnTrain = new MutableCargoBundle();
expectedOnTrain.setAmount(this.cargoType0FromStation2, 30);
expectedOnTrain.setAmount(this.cargoType0FromStation0, 50);
assertEquals(expectedAtStation.toImmutableCargoBundle(),
getCargoAtStation());
assertEquals(expectedOnTrain.toImmutableCargoBundle(),
getCargoOnTrain());
}
/**
* Tests that a train drops of cargo that a station demands and does not
* drop off cargo that is not demanded unless it has to.
*/
public void testDropOffCargo() {
// Set the station to demand cargo type 0.
StationModel station = (StationModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
0);
Demand4Cargo demand = new Demand4Cargo(new boolean[] { true,
false, false, false });
station = new StationModel(station, demand);
w.set(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, 0, station);
// Check that the station demands what we think it does.
assertTrue("The station should demand cargo type 0.", station
.getDemand().isCargoDemanded(0));
assertFalse("The station shouldn't demand cargo type 1.", station
.getDemand().isCargoDemanded(1));
// Add 2 wagons for cargo type 0 and 1 for cargo type 1 to train.
ImInts wagons = new ImInts(0, 0, 1, 1);
addWagons(wagons);
// Add quantities of cargo type 0 and 2 to the train.
setCargoOnTrain(this.cargoType0FromStation2, 50);
setCargoOnTrain(this.cargoType1FromStation2, 40);
stopAtStation();
/*
* The train should have dropped of the 50 units cargo of type 0 since
* the station demands it but not the 40 units of cargo type 1 which is
* does not demand.
*/
MutableCargoBundle expectedOnTrain = new MutableCargoBundle();
expectedOnTrain.setAmount(this.cargoType1FromStation2, 40);
assertEquals(expectedOnTrain.toImmutableCargoBundle(),
getCargoOnTrain());
assertEquals(ImmutableCargoBundle.EMPTY_BUNDLE, getCargoAtStation());
// Now remove the wagons from the train.
removeAllWagonsFromTrain();
stopAtStation();
/*
* This time the train has no wagons, so has to drop the 40 units of
* cargo type 1 even though the station does not demand it. Since ths
* station does not demand it, it is added to the cargo waiting at the
* station.
*/
MutableCargoBundle expectedAtStation = new MutableCargoBundle();
expectedAtStation.setAmount(this.cargoType1FromStation2, 40);
assertEquals(expectedAtStation.toImmutableCargoBundle(),
getCargoAtStation());
assertEquals(ImmutableCargoBundle.EMPTY_BUNDLE, getCargoOnTrain());
}
/**
* Tests that a train does not drop cargo off at its station of origin
* unless it has to.
*/
public void testDontDropOffCargo() {
// Set station to
setCargoOnTrain(cargoType0FromStation0, 50);
setCargoOnTrain(cargoType0FromStation2, 50);
stopAtStation();
// The train shouldn't have dropped anything off.
MutableCargoBundle expectedOnTrain = new MutableCargoBundle();
expectedOnTrain.setAmount(cargoType0FromStation0, 50);
expectedOnTrain.setAmount(cargoType0FromStation2, 50);
assertEquals(expectedOnTrain.toImmutableCargoBundle(),
getCargoOnTrain());
assertEquals(ImmutableCargoBundle.EMPTY_BUNDLE, getCargoAtStation());
// Now remove the wagons from the train.
removeAllWagonsFromTrain();
stopAtStation();
/*
* The train now has no wagons, so must drop off the cargo whether the
* station demands it or not. Since the station does not demand it, the
* cargo should get added to the cargo waiting at the station.
*/
MutableCargoBundle expectedAtStation = new MutableCargoBundle();
expectedAtStation.setAmount(cargoType0FromStation0, 50);
expectedAtStation.setAmount(cargoType0FromStation2, 50);
assertEquals(expectedAtStation.toImmutableCargoBundle(),
getCargoAtStation());
assertEquals(ImmutableCargoBundle.EMPTY_BUNDLE, getCargoOnTrain());
}
/**
* Tests that a train drops off any cargo before picking up cargo.
*/
public void testPickUpAndDropOffSameCargoType() {
// Set cargo at station and on train.
setCargoOnTrain(this.cargoType0FromStation2, 120);
setCargoAtStation(this.cargoType0FromStation0, 200);
// Set station to demand cargo 0.
StationModel station = (StationModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
0);
Demand4Cargo demand = new Demand4Cargo(new boolean[] { true,
false, false, false });
station = new StationModel(station, demand);
w.set(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, 0, station);
assertTrue(station.getDemand().isCargoDemanded(0));
stopAtStation();
MutableCargoBundle expectedOnTrain = new MutableCargoBundle();
expectedOnTrain.setAmount(this.cargoType0FromStation0, 120);
MutableCargoBundle expectedAtStation = new MutableCargoBundle();
expectedAtStation.setAmount(this.cargoType0FromStation0, 80);
assertEquals(expectedOnTrain.toImmutableCargoBundle(),
getCargoOnTrain());
assertEquals(expectedAtStation.toImmutableCargoBundle(),
getCargoAtStation());
}
private void removeAllWagonsFromTrain() {
addWagons(new ImInts());
}
private void addWagons(ImInts wagons) {
TrainModel train = (TrainModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.TRAINS,
0);
TrainModel newTrain = train.getNewInstance(train.getEngineType(),
wagons);
w.set(MapFixtureFactory.TEST_PRINCIPAL, KEY.TRAINS, 0, newTrain);
}
private void stopAtStation() {
DropOffAndPickupCargoMoveGenerator moveGenerator = new DropOffAndPickupCargoMoveGenerator(
0, 0, w, MapFixtureFactory.TEST_PRINCIPAL, false, false);
Move m = moveGenerator.generateMove();
if(null != m){
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
assertEquals(MoveStatus.MOVE_OK, ms);
}
}
/**
* Retrieves the cargo bundle that is waiting at the station from the world
* object.
*/
private ImmutableCargoBundle getCargoAtStation() {
StationModel station = (StationModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
0);
ImmutableCargoBundle cargoAtStation = (ImmutableCargoBundle) w.get(
MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES,
station.getCargoBundleID());
return cargoAtStation;
}
/**
* Retrieves the cargo bundle that the train is carrying from the world
* object.
*/
private ImmutableCargoBundle getCargoOnTrain() {
TrainModel train = (TrainModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.TRAINS,
0);
ImmutableCargoBundle cargoOnTrain = (ImmutableCargoBundle) w.get(
MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES,
train.getCargoBundleID());
return cargoOnTrain;
}
private void setCargoAtStation(CargoBatch cb, int amount) {
StationModel station = (StationModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
0);
MutableCargoBundle bundle = new MutableCargoBundle(getCargoAtStation());
bundle.setAmount(cb, amount);
w.set(MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES, station.getCargoBundleID(), bundle
.toImmutableCargoBundle());
}
private void setCargoOnTrain(CargoBatch cb, int amount) {
TrainModel train = (TrainModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.TRAINS,
0);
MutableCargoBundle bundle = new MutableCargoBundle(getCargoOnTrain());
bundle.setAmount(cb, amount);
w.set(MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES, train.getCargoBundleID(), bundle
.toImmutableCargoBundle());
}
public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}
private static junit.framework.Test suite() {
junit.framework.TestSuite testSuite = new junit.framework.TestSuite(
DropOffAndPickupCargoMoveGeneratorTest.class);
return testSuite;
}
}

TrackPathFinderTest

Full name: jfreerails.controller.TrackPathFinderTest

Documentation

/**
* JUnit test for TrackPathFinder.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test for TrackPathFinder.
*
* @author Luke
*
*/
public class TrackPathFinderTest extends TestCase {
private WorldImpl world;
private Player testPlayer = new Player("test", 0);
@Override
protected void setUp() throws Exception {
world = new WorldImpl(20, 20);
world.addPlayer(testPlayer);
world.set(ITEM.GAME_RULES, GameRules.NO_RESTRICTIONS);
MapFixtureFactory.generateTrackRuleList(world);
}
public void testGeneratePath() {
try {
BuildTrackStrategy bts = BuildTrackStrategy.getSingleRuleInstance(
0, world);
TrackPathFinder pathFinder = new TrackPathFinder(world, testPlayer
.getPrincipal());
List l = pathFinder.generatePath(new ImPoint(0, 0), new ImPoint(0,
5), bts);
assertEquals(5, l.size());
List list2 = pathFinder.generatePath(new ImPoint(5, 5),
new ImPoint(5, 10), bts);
assertEquals(5, list2.size());
list2 = pathFinder.generatePath(new ImPoint(5, 10), new ImPoint(5,
5), bts);
assertEquals(5, list2.size());
} catch (PathNotFoundException e) {
fail();
}
}
}

OpenListTest

Full name: jfreerails.controller.OpenListTest

Documentation

/**
* Test class for the OpenList class, verifying its core functionalities including
* containment checks, smallest F value retrieval, size management, and addition operations.
* This class contains unit tests to ensure the correctness of the OpenList implementation.
*
* @see OpenList
*/

Source Code

public class OpenListTest extends TestCase {
public void testGetF() {
}
public void testContains() {
OpenList openList = new OpenList();
assertFalse(openList.contains(0));
openList.add(0, 4);
assertTrue(openList.contains(0));
assertFalse(openList.contains(4));
openList.popNodeWithSmallestF();
assertFalse(openList.contains(0));
}
public void testSmallestF() {
OpenList openList = new OpenList();
openList.add(0, 4);
assertEquals(4, openList.smallestF());
openList.add(1, 5);
assertEquals(4, openList.smallestF());
openList.add(5, 1);
assertEquals(1, openList.smallestF());
openList.popNodeWithSmallestF();
assertEquals(4, openList.smallestF());
openList.popNodeWithSmallestF();
assertEquals(5, openList.smallestF());
}
public void testSize() {
OpenList openList = new OpenList();
assertEquals(0, openList.size());
openList.add(0, 4);
assertEquals(1, openList.size());
openList.popNodeWithSmallestF();
assertEquals(0, openList.size());
}
public void testAdd() {
OpenList openList = new OpenList();
openList.add(1, 4);
assertEquals(1, openList.size());
assertEquals(4, openList.smallestF());
openList.add(1, 6);
assertEquals(1, openList.size());
assertEquals(6, openList.smallestF());
}
}

StockPriceCalculatorTest

Full name: jfreerails.controller.StockPriceCalculatorTest

Documentation

/**
* Unit tests for the StockPriceCalculator class, verifying the behavior of its methods
* including checking if a year is the first year, calculating net worth, tracking profits
* from the last year, and computing stock prices based on game time and transactions.
* This class uses helper methods to manage time progression and transaction additions
* for test scenarios.
*
* @see jfreerails.controller.StockPriceCalculator
*/

Source Code

public class StockPriceCalculatorTest extends TestCase {
World w;
StockPriceCalculator calc;
@Override
protected void setUp() throws Exception {
super.setUp();
w = MapFixtureFactory2.getCopy();
calc = new StockPriceCalculator(w);
}
/*
* Test method for
* 'jfreerails.controller.StockPriceCalculator.isFirstYear(int)'
*/
public void testIsFirstYear() {
assertTrue(calc.isFirstYear(0));
GameCalendar calendar = (GameCalendar) w.get(ITEM.CALENDAR);
int tpy = calendar.getTicksPerYear();
int currentTicks = w.currentTime().getTicks();
GameTime newTime = new GameTime(currentTicks + tpy + 1);
w.setTime(newTime);
assertFalse(calc.isFirstYear(0));
newTime = new GameTime(currentTicks + tpy - 1);
w.setTime(newTime);
assertTrue(calc.isFirstYear(0));
}
/*
* Test method for
* 'jfreerails.controller.StockPriceCalculator.netWorth(int)'
*/
public void testNetWorth() {
long initialNetworth = 500000;
assertEquals(initialNetworth, calc.netWorth(0));
int currentTicks = w.currentTime().getTicks();
GameTime newTime = new GameTime(currentTicks + 1);
w.setTime(newTime);
CargoBatch batch = new CargoBatch(0, 0, 0, 0, 0);
long income = 100000;
Transaction t = new DeliverCargoReceipt(new Money(income), 10, 0,
batch, 0);
FreerailsPrincipal princ = w.getPlayer(0).getPrincipal();
w.addTransaction(princ, t);
assertEquals(initialNetworth, calc.netWorth(0));
GameCalendar calendar = (GameCalendar) w.get(ITEM.CALENDAR);
int tpy = calendar.getTicksPerYear();
currentTicks = w.currentTime().getTicks();
newTime = new GameTime(currentTicks + tpy);
w.setTime(newTime);
long expectedNetWorth = initialNetworth + income;
assertEquals(expectedNetWorth, calc.netWorth(0));
}
private void advanceTimeOneTick() {
int currentTicks = w.currentTime().getTicks();
GameTime newTime = new GameTime(currentTicks + 1);
w.setTime(newTime);
}
private void advanceTimeOneYear() {
GameCalendar calendar = (GameCalendar) w.get(ITEM.CALENDAR);
int tpy = calendar.getTicksPerYear();
int currentTicks = w.currentTime().getTicks();
GameTime newTime = new GameTime(currentTicks + tpy);
w.setTime(newTime);
}
/*
* Test method for
* 'jfreerails.controller.StockPriceCalculator.profitsLastYear(int)'
*/
public void testProfitsLastYear() {
assertEquals(0, calc.profitsLastYear(0));
int currentTicks = w.currentTime().getTicks();
GameTime newTime = new GameTime(currentTicks + 10);
w.setTime(newTime);
assertEquals(0, calc.profitsLastYear(0));
long income = 100000;
addIncome(income);
assertEquals(0, calc.profitsLastYear(0));
advanceTimeOneYear();
assertEquals(income, calc.profitsLastYear(0));
}
private void addIncome(long income) {
CargoBatch batch = new CargoBatch(0, 0, 0, 0, 0);
Transaction t = new DeliverCargoReceipt(new Money(income), 10, 0,
batch, 0);
FreerailsPrincipal princ = w.getPlayer(0).getPrincipal();
w.addTransaction(princ, t);
}
public void testCalculate() {
Money stockPrice = calc.calculate()[0].currentPrice;
assertEquals(new Money(10), stockPrice);
advanceTimeOneTick();
addIncome(100000);
calc.calculate();
stockPrice = calc.calculate()[0].currentPrice;
assertEquals(new Money(10), stockPrice);
advanceTimeOneYear();
calc.calculate();
stockPrice = calc.calculate()[0].currentPrice;
assertEquals(new Money(11), stockPrice);
}
}

GenerateDependenciesXmlAndHtmlTest

Full name: experimental.GenerateDependenciesXmlAndHtmlTest

Documentation

/**
* JUnit test for GenerateDependenciesXmlAndHtml.
*
* @author Luke
*
*/

Source Code

/**
* JUnit test for GenerateDependenciesXmlAndHtml.
*
* @author Luke
*
*/
public class GenerateDependenciesXmlAndHtmlTest extends TestCase {
public void testIsPackageNameOk() {
assertTrue(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/*"));
assertFalse(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails.*"));
assertTrue(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/trees/*"));
assertFalse(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/trees/branches*"));
assertTrue(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/trees/branches/*"));
assertFalse(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/trees/branches/**/"));
assertTrue(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/trees/branches/**/*"));
assertTrue(GenerateDependenciesXmlAndHtml
.isPackageNameOk("it/unimi/dsi/fastUtil/*")); // note upper
// case in
// package name.
}
}

PositionOnTrack

Full name: jfreerails.world.common.PositionOnTrack

Documentation

/**
* A <b>mutable</b> class that stores the coordinates of the tile on entity is
* standing on and the direction in which the entity is facing (usually the
* direction the entity as just been moving - the opposite to the direction it
* came from), it provides methods to encode and decode its field values to and
* from a single int.
*
* @author Luke
*/

Source Code

/**
* A <b>mutable</b> class that stores the coordinates of the tile on entity is
* standing on and the direction in which the entity is facing (usually the
* direction the entity as just been moving - the opposite to the direction it
* came from), it provides methods to encode and decode its field values to and
* from a single int.
*
* @author Luke
*/
public final class PositionOnTrack implements FreerailsMutableSerializable {
private static final int BITS_FOR_COORDINATE = 14;
private static final int BITS_FOR_DIRECTION = 3;
public static final int MAX_COORDINATE = (1 << BITS_FOR_COORDINATE) - 1;
public static final int MAX_DIRECTION = (1 << BITS_FOR_DIRECTION) - 1;
private static final long serialVersionUID = 3257853198755707184L;
public static PositionOnTrack createComingFrom(int x, int y, Step direction) {
return new PositionOnTrack(x, y, direction);
}
public static PositionOnTrack createFacing(int x, int y, Step direction) {
return new PositionOnTrack(x, y, direction.getOpposite());
}
public static PositionOnTrack[] fromInts(int[] ints) {
PositionOnTrack[] returnValue = new PositionOnTrack[ints.length];
for (int i = 0; i < ints.length; i++) {
PositionOnTrack p = new PositionOnTrack(ints[i]);
returnValue[i] = p;
}
return returnValue;
}
public static int[] toInts(PositionOnTrack[] pos) {
int[] returnValue = new int[pos.length];
for (int i = 0; i < pos.length; i++) {
returnValue[i] = pos[i].toInt();
}
return returnValue;
}
/** The direction from which we entered the tile. */
private Step cameFrom = Step.NORTH;
private int x = 0;
private int y = 0;
public PositionOnTrack() {
}
public PositionOnTrack(int i) {
this.setValuesFromInt(i);
}
private PositionOnTrack(int x, int y, Step direction) {
if (x > MAX_COORDINATE || x < 0) {
throw new IllegalArgumentException("x=" + x);
}
if (y > MAX_COORDINATE || y < 0) {
throw new IllegalArgumentException("y=" + y);
}
this.x = x;
this.y = y;
this.cameFrom = direction;
}
/**
* @return The direction the entity came from.
*/
public Step cameFrom() {
return cameFrom;
}
@Override
public boolean equals(Object o) {
if (null == o) {
return false;
}
if (o instanceof PositionOnTrack) {
PositionOnTrack other = (PositionOnTrack) o;
if (other.cameFrom() == this.cameFrom()
&& other.getX() == this.getX()
&& other.getY() == this.getY()) {
return true;
}
return false;
}
return false;
}
/**
* @return The direction the entity is facing.
*/
public Step facing() {
return cameFrom.getOpposite();
}
/**
* @return the position on the track which is in the opposite direction.
*/
public PositionOnTrack getOpposite() {
int newX = this.getX() - this.cameFrom.deltaX;
int newY = this.getY() - this.cameFrom.deltaY;
Step newDirection = this.cameFrom.getOpposite();
return createComingFrom(newX, newY, newDirection);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public int hashCode() {
int result;
result = x;
result = 29 * result + y;
result = 29 * result + cameFrom.hashCode();
return result;
}
public void setCameFrom(Step v) {
this.cameFrom = v;
}
public void setFacing(Step v) {
this.cameFrom = v.getOpposite();
}
public void setValuesFromInt(int i) {
x = i & MAX_COORDINATE;
int shiftedY = i & (MAX_COORDINATE << BITS_FOR_COORDINATE);
y = shiftedY >> BITS_FOR_COORDINATE;
int shiftedDirection = i & (MAX_DIRECTION << (2 * BITS_FOR_COORDINATE));
int directionAsInt = shiftedDirection >> (2 * BITS_FOR_COORDINATE);
cameFrom = Step.getInstance(directionAsInt);
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void move(Step step) {
this.x += step.deltaX;
this.y += step.deltaY;
this.cameFrom = step.getOpposite();
}
/**
* @return an integer representing this PositionOnTrack object
*/
public int toInt() {
int i = x | (y << BITS_FOR_COORDINATE);
int directionAsInt = cameFrom.getID();
int shiftedDirection = (directionAsInt << (2 * BITS_FOR_COORDINATE));
i = i | shiftedDirection;
return i;
}
public static int toInt(int x, int y) {
int i = x | (y << BITS_FOR_COORDINATE);
return i;
}
@Override
public String toString() {
String s = "PositionOnTrack: " + x + ", " + y + " facing "
+ cameFrom.getOpposite().toString();
return s;
}
}

Step

Full name: jfreerails.world.common.Step

Documentation

/**
* This class represents a movement from a tile to any one of the surrounding
* eight tiles.
*
* @author Luke
*/

Source Code

/**
* This class represents a movement from a tile to any one of the surrounding
* eight tiles.
*
* @author Luke
*/
@jfreerails.util.InstanceControlled
final public class Step implements FlatTrackTemplate {
private static final long serialVersionUID = 3256444698640921912L;
public static final int TILE_DIAMETER = Constants.TILE_SIZE;
public static final double TILE_DIAGONAL = StrictMath.hypot(TILE_DIAMETER,
TILE_DIAMETER);
/** North. */
public static final Step NORTH;
/** West. */
public static final Step WEST;
/** South East. */
public static final Step SOUTH_EAST;
/** North-East. */
public static final Step NORTH_EAST;
/** East. */
public static final Step EAST;
/** South. */
public static final Step SOUTH;
/** South West. */
public static final Step SOUTH_WEST;
/** North West. */
public static final Step NORTH_WEST;
/**
* A 3x3 array of OneTileMoveVectors, representing vectors to eight adjacent
* tiles plus a zero-distance vector.
*/
private static final Step[][] vectors;
/**
* Another array of OneTileMoveVectors representing the 8 compass directions
* going clockwise from North.
*/
private static Step[] list;
static {
vectors = setupVectors();
NORTH = getInstance(0, -1);
WEST = getInstance(-1, 0);
SOUTH_EAST = getInstance(1, 1);
NORTH_EAST = getInstance(1, -1);
EAST = getInstance(1, 0);
SOUTH = getInstance(0, 1);
SOUTH_WEST = getInstance(-1, 1);
NORTH_WEST = getInstance(-1, -1);
list = new Step[8];
list[0] = NORTH;
list[1] = NORTH_EAST;
list[2] = EAST;
list[3] = SOUTH_EAST;
list[4] = SOUTH;
list[5] = SOUTH_WEST;
list[6] = WEST;
list[7] = NORTH_WEST;
}
private static Step[][] setupVectors() {
int t = 1;
Step[][] tvectors = new Step[3][3];
for (int y = -1; y <= 1; y++) {
for (int x = -1; x <= 1; x++) {
if ((0 != x) || (0 != y)) {
tvectors[x + 1][y + 1] = new Step(x, y, t);
}
t = t << 1;
}
}
return tvectors;
}
public static ImPoint move(ImPoint p, Step... path) {
int x = p.x;
int y = p.y;
for (Step v : path) {
x += v.deltaX;
y += v.deltaY;
}
return new ImPoint(x, y);
}
/** The X and Y components of the vector. */
public final int deltaX;
/** The X and Y components of the vector. */
public final int deltaY;
private final int flatTrackTemplate;
private final double length;
/** Returns the X component of the vector. */
public int getDx() {
return deltaX;
}
/** Returns the Y component of the vector. */
public int getDy() {
return deltaY;
}
/**
* Returns a new oneTileMoveVector whose direction is opposite to that the
* current one.
*
* @return A oneTileMoveVector.
*/
public Step getOpposite() {
return getInstance(this.deltaX * -1, this.deltaY * -1);
}
/**
* Returns the name of the vector. E.g. "north-east"
*
* @return the name.
*/
@Override
public String toString() {
String name;
switch (deltaY) {
case 1:
name = " south";
break;
case -1:
name = " north";
break;
default:
name = "";
break;
}
switch (deltaX) {
case 1:
name += " east";
break;
case -1:
name += " west";
break;
default:
break;
}
return name;
}
public String toAbrvString() {
String name;
switch (deltaY) {
case 1:
name = "s";
break;
case -1:
name = "n";
break;
default:
name = "";
break;
}
switch (deltaX) {
case 1:
name += "e";
break;
case -1:
name += "w";
break;
default:
break;
}
return name;
}
/**
* Create a new OneTileMoveVector. N.B Private constructor to enforce enum
* property, use getInstance(x,y) instead. Pass values for delta X and Y:
* they must be in the range -1 to 1 and cannot both be equal to 0.
*
* @param x
* Tile coordinate.
* @param y
* Tile coordinate
* @param t
* an integer representing the track template this vector
* corresponds to.
*/
private Step(int x, int y, int t) {
deltaX = x;
deltaY = y;
flatTrackTemplate = t;
length = (x * y) == 0 ? TILE_DIAMETER : TILE_DIAGONAL;
}
public static Step getInstance(int number) {
return list[number];
}
public static boolean checkValidity(ImPoint a, ImPoint b) {
int dx = b.x - a.x;
int dy = b.y - a.y;
return checkValidity(dx, dy);
}
public static Step getInstance(int dx, int dy) {
if ((((dx < -1) || (dx > 1)) || ((dy < -1) || (dy > 1)))
|| ((dx == 0) && (dy == 0))) {
throw new IllegalArgumentException(
dx
+ " and "
+ dy
+ ": The values passed both must be integers in the range -1 to 1, and not both equal 0.");
}
return vectors[dx + 1][dy + 1];
}
/**
* Returns true if the values passed could be used to create a valid vector.
*/
public static boolean checkValidity(int x, int y) {
if ((((x < -1) || (x > 1)) || ((y < -1) || (y > 1)))
|| ((x == 0) && (y == 0))) {
return false;
}
return true;
}
public ImPoint createRelocatedPoint(ImPoint from) {
return new ImPoint(from.x + deltaX, from.y + deltaY);
}
public boolean contains(FlatTrackTemplate ftt) {
if (ftt.get9bitTemplate() == this.flatTrackTemplate) {
return true;
}
return false;
}
public int get9bitTemplate() {
return flatTrackTemplate;
}
/**
* @return a copy of the list of 8 OneTileMoveVectors going clockwise from
* North.
*/
public static Step[] getList() {
return list.clone(); // defensive copy.
}
/**
* @return the length of this vector. Each tile is 100 units x 100 units.
*/
public double getLength() {
return length;
}
/**
*
* @return compass bearing in radians.
*/
public double getDirection() {
int i = 0;
while (this != list[i]) {
i++;
}
return 2 * Math.PI / 8 * i;
}
/**
* @return a number representing the compass point this vector indicates,
* with 0 representing North, 1 NorthEast, 2 East and so on.
*/
public int getID() {
int i = 0;
while (this != list[i]) {
i++;
}
return i;
}
private Object readResolve() throws ObjectStreamException {
return Step.getInstance(this.deltaX, this.deltaY);
}
/**
* @return the OneTileMoveVector nearest in orientation to the specified dx,
* dy
*/
public static Step getNearestVector(int dx, int dy) {
if (0 == dx * dy) {
if (dx > 0) {
return EAST;
} else if (dx != 0) {
return WEST;
} else if (dy > 0) {
return SOUTH;
} else {
return NORTH;
}
}
double gradient = dy;
gradient = gradient / dx;
double B = 2;
double A = 0.5;
double C = -2;
double D = -0.5;
if (gradient > B) {
if (dy < 0) {
return NORTH;
}
return SOUTH;
} else if (gradient > A) {
if (dy > 0) {
return SOUTH_EAST;
}
return NORTH_WEST;
} else if (gradient > D) {
if (dx > 0) {
return EAST;
}
return WEST;
} else if (gradient > C) {
if (dx < 0) {
return SOUTH_WEST;
}
return NORTH_EAST;
} else {
if (dy > 0) {
return SOUTH;
}
return NORTH;
}
}
public boolean isDiagonal() {
return 0 != deltaX * deltaY;
}
public int get8bitTemplate() {
return 1 << this.getID();
}
}

ImSet

Full name: jfreerails.world.common.ImSet

Documentation

/**
* An immutable set.
*
* @author Luke
*
*/

Source Code

/**
* An immutable set.
*
* @author Luke
*
*/
@Immutable
public final class ImSet<E extends FreerailsSerializable> implements
FreerailsSerializable {
private static final long serialVersionUID = -8075637749158447780L;
private final HashSet<E> hashSet;
public ImSet(Set<E> data) {
hashSet = new HashSet<E>(data);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImSet))
return false;
final ImSet imSet = (ImSet) o;
if (!hashSet.equals(imSet.hashSet))
return false;
return true;
}
@Override
public int hashCode() {
return hashSet.hashCode();
}
public boolean contains(E element) {
return hashSet.contains(element);
}
}

ImInts

Full name: jfreerails.world.common.ImInts

Documentation

/**
* An immutable list of ints.
*
* @author Luke
*
*/

Source Code

/**
* An immutable list of ints.
*
* @author Luke
*
*/
@Immutable
public class ImInts implements FreerailsSerializable {
private static final long serialVersionUID = -7171552118713000676L;
private final int ints[];
public ImInts(int... i) {
this.ints = i.clone();
}
public static ImInts fromBoolean(boolean... i) {
int[] ii = new int[i.length];
for (int j = 0; j < i.length; j++) {
ii[j] = i[j] ? 1 : 0;
}
return new ImInts(ii);
}
public int size() {
return ints.length;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImInts))
return false;
final ImInts other = (ImInts) o;
if (!Arrays.equals(ints, other.ints))
return false;
return true;
}
@Override
public int hashCode() {
return ints.length;
}
public int get(int i) {
return ints[i];
}
public ImInts removeLast() {
int[] newInts = new int[ints.length - 1];
System.arraycopy(ints, 0, newInts, 0, newInts.length);
return new ImInts(newInts);
}
public ImInts append(int... extra) {
int[] newInts = new int[ints.length + extra.length];
System.arraycopy(ints, 0, newInts, 0, ints.length);
System.arraycopy(extra, 0, newInts, ints.length, extra.length);
return new ImInts(newInts);
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer(getClass().getName());
sb.append("[");
for (int i = 0; i < ints.length; i++) {
sb.append(ints[i]);
if (i + 1 < ints.length)
sb.append(", ");
}
sb.append("]");
return sb.toString();
}
/** Returns the sum of the ints stored in the list.*/
public int sum(){
int sum = 0;
for (int i = 0; i < ints.length; i++) {
sum+=ints[i];
}
return sum;
}
}

ImList

Full name: jfreerails.world.common.ImList

Documentation

/**
* An immutable List
*
* @author Luke
*
*/

Source Code

/**
* An immutable List
*
* @author Luke
*
*/
@Immutable
public final class ImList<E extends FreerailsSerializable> implements
FreerailsSerializable {
private static final long serialVersionUID = 2669191159273299313L;
private final E[] elementData;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImList))
return false;
final ImList imList = (ImList) o;
if (!Arrays.equals(elementData, imList.elementData))
return false;
return true;
}
@Override
public int hashCode() {
return elementData.length;
}
@SuppressWarnings("unchecked")
public ImList(E... items) {
elementData = (E[]) new FreerailsSerializable[items.length];
for (int i = 0; i < items.length; i++) {
elementData[i] = items[i];
}
}
@SuppressWarnings("unchecked")
public ImList(List<E> list) {
elementData = (E[]) new FreerailsSerializable[list.size()];
for (int i = 0; i < list.size(); i++) {
elementData[i] = list.get(i);
}
}
public void checkForNulls() throws NullPointerException {
for (int i = 0; i < elementData.length; i++) {
if (null == elementData[i])
throw new NullPointerException();
}
}
public int size() {
return elementData.length;
}
public E get(int i) {
return elementData[i];
}
}

FreerailsPathIterator

Full name: jfreerails.world.common.FreerailsPathIterator

Documentation

/**
* This interface lets the caller retrieve a path made up of a series of
* straight lines. E.g. it lets the path a train takes across a section of track
* be retrieved without revealing the underlying objects that represent the
* track.
*
* @author luke
*/

Source Code

/**
* This interface lets the caller retrieve a path made up of a series of
* straight lines. E.g. it lets the path a train takes across a section of track
* be retrieved without revealing the underlying objects that represent the
* track.
*
* @author luke
*/
public interface FreerailsPathIterator extends FreerailsMutableSerializable {
/**
* Tests whether the path has another segment.
*/
boolean hasNext();
/**
* Gets the next segment of the path and places its coordinates in the
* specified IntLine; then moves the iterator forwards by one path segment.
* (The coordinates are placed the passed-in IntLine rather than a new
* object to avoid the cost of object creation.)
*
* @param line
*/
void nextSegment(IntLine line);
}

Activity

Full name: jfreerails.world.common.Activity

Documentation

/**
* Represents an activity with a duration and state transitions over time.
* This interface defines methods to retrieve the duration of the activity
* and to determine its state at a given time delta.
*
* @see FreerailsSerializable
*/

Source Code

public interface Activity<E extends FreerailsSerializable> extends
FreerailsSerializable {
double duration();
E getState(double dt);
}

Methods

FreerailsPathIteratorImpl

Full name: jfreerails.world.common.FreerailsPathIteratorImpl

Documentation

/**
* Lets the caller access a series of Points as a series of IntLines.
*
* @author Luke Lindsay
*/

Source Code

/**
* Lets the caller access a series of Points as a series of IntLines.
*
* @author Luke Lindsay
*/
public class FreerailsPathIteratorImpl implements FreerailsPathIterator {
private static final long serialVersionUID = 3258411750679720758L;
public static FreerailsPathIterator forwardsIterator(List<Point> l) {
return new FreerailsPathIteratorImpl(l, true);
}
public static FreerailsPathIterator backwardsIterator(List<Point> l) {
return new FreerailsPathIteratorImpl(l, false);
}
/** Creates new FreerailsPathIteratorImpl */
public FreerailsPathIteratorImpl(List<Point> l, boolean f) {
points = l;
forwards = f;
if (forwards) {
this.position = 0;
} else {
this.position = l.size() - 1; // The last element of a list of
// size 7 is at position 6.
}
}
private final boolean forwards;
private int position;
private final List<Point> points;
public boolean hasNext() {
if (forwards) {
return (position + 1) < points.size();
}
return (position - 1) >= 0;
}
public void nextSegment(IntLine line) {
if (hasNext()) {
Point a;
Point b;
if (forwards) {
position++;
a = points.get(position - 1);
b = points.get(position);
} else {
position--;
a = points.get(position + 1);
b = points.get(position);
}
line.x1 = a.x;
line.y1 = a.y;
line.x2 = b.x;
line.y2 = b.y;
} else {
throw new NoSuchElementException();
}
}
}

Money

Full name: jfreerails.world.common.Money

Documentation

/**
* Represents an amount of Money.
*
* @author Luke
*/

Source Code

/**
* Represents an amount of Money.
*
* @author Luke
*/
final public class Money implements FreerailsSerializable {
private static final long serialVersionUID = 3258697615163338805L;
public static final Money ZERO = new Money(0);
private static final DecimalFormat df = new DecimalFormat("#,###");
private final long amount;
public long getAmount() {
return amount;
}
@Override
public int hashCode() {
return (int) (amount ^ (amount >>> 32));
}
@Override
public String toString() {
return df.format(amount);
}
public Money(long amount) {
this.amount = amount;
}
public Money changeSign() {
return new Money(-amount);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Money) {
Money test = (Money) obj;
return test.amount == this.amount;
}
return false;
}
}

IntLine

Full name: jfreerails.world.common.IntLine

Documentation

/**
* This class defines a straight line between two points. Units are arbitrary.
*
* @author Luke
*/

Source Code

/**
* This class defines a straight line between two points. Units are arbitrary.
*
* @author Luke
*/
public class IntLine implements Serializable {
private static final long serialVersionUID = 3257853198755705393L;
private final static int MAX_SQUAREROOTS = 64 * 256;
private final static double squareRoots[];
static {
squareRoots = new double[MAX_SQUAREROOTS];
for (int i = 0; i < MAX_SQUAREROOTS; i++) {
squareRoots[i] = Math.sqrt(i);
}
}
public int x1;
public int x2;
public int y1;
public int y2;
@Override
public int hashCode() {
int result;
result = x1;
result = 29 * result + x2;
result = 29 * result + y1;
result = 29 * result + y2;
return result;
}
/**
* @return the length of the line
*/
public double getLength() {
int sumOfSquares = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
if(sumOfSquares < MAX_SQUAREROOTS) {
return squareRoots[sumOfSquares];
}
return Math.sqrt(sumOfSquares);
}
/**
* @param xx1
* x of the first point
* @param yy1
* y of the first point
* @param xx2
* x of the second point
* @param yy2
* y of the second point
*/
public IntLine(int xx1, int yy1, int xx2, int yy2) {
x1 = xx1;
y1 = yy1;
x2 = xx2;
y2 = yy2;
}
/**
* Default constructor - defines a dot at 0,0.
*/
public IntLine() {
}
@Override
public boolean equals(Object o) {
if (null == o) {
return false;
}
if (o == this) {
return true;
}
if (o instanceof IntLine) {
IntLine line = (IntLine) o;
if (line.x1 == this.x1 && line.x2 == this.x2 && line.y1 == this.y1
&& line.y2 == this.y2) {
return true;
}
return false;
}
return false;
}
@Override
public String toString() {
return "(" + x1 + ", " + y1 + ", " + x2 + ", " + y2 + ")";
}
}

FreerailsMutableSerializable

Full name: jfreerails.world.common.FreerailsMutableSerializable

Documentation

/**
* This interface tags mutable serializable classes.
*
* @author Luke
*/

Source Code

/**
* This interface tags mutable serializable classes.
*
* @author Luke
*/
public interface FreerailsMutableSerializable extends Serializable {
}

Methods

No methods found

GameCalendar

Full name: jfreerails.world.common.GameCalendar

Documentation

/**
* This class converts time measured in ticks since the game began into time
* represented as <i>Month, Year</i> and <i>hour:minute</i>.
*
* @author Luke
*/

Source Code

/**
* This class converts time measured in ticks since the game began into time
* represented as <i>Month, Year</i> and <i>hour:minute</i>.
*
* @author Luke
*/
final public class GameCalendar implements FreerailsSerializable {
private static final long serialVersionUID = 3257568421033226805L;
private static final DecimalFormat decimalFormat = new DecimalFormat("00");
private final int ticksPerYear;
private final int startYear;
@Override
public int hashCode() {
int result;
result = ticksPerYear;
result = 29 * result + startYear;
return result;
}
public GameTime getStartOfYear(GameTime t) {
int year = getYear(t.getTicks());
int ticks = getTicks(year);
return new GameTime(ticks);
}
public String getYearAsString(int ticks) {
int i = getYear(ticks);
return String.valueOf(i);
}
public int getYear(int ticks) {
return startYear + (ticks / ticksPerYear);
}
public int getTicks(int year) {
int deltaYear = year - startYear;
return deltaYear * ticksPerYear;
}
/**
* Returns the time of day as a string, note that a year is made up of a
* representative day, so 1st June is equivalent to 12 noon.
*/
public String getTimeOfDay(int i) {
int ticksPerHour = ticksPerYear / 24;
int hour = ticksPerHour == 0 ? 0 : (i % ticksPerYear) / ticksPerHour;
int ticksPerMinute = ticksPerYear / (24 * 60);
int minute = ticksPerMinute == 0 ? 0 : (i % (ticksPerMinute * 60));
return decimalFormat.format(hour) + ":" + decimalFormat.format(minute);
}
public String getYearAndMonth(int i) {
int month = getMonth(i);
String monthAbrev = null;
switch (month) {
case 0: {
monthAbrev = "Jan";
break;
}
case 1: {
monthAbrev = "Feb";
break;
}
case 2: {
monthAbrev = "Mar";
break;
}
case 3: {
monthAbrev = "Apr";
break;
}
case 4: {
monthAbrev = "May";
break;
}
case 5: {
monthAbrev = "Jun";
break;
}
case 6: {
monthAbrev = "Jul";
break;
}
case 7: {
monthAbrev = "Aug";
break;
}
case 8: {
monthAbrev = "Sep";
break;
}
case 9: {
monthAbrev = "Oct";
break;
}
case 10: {
monthAbrev = "Nov";
break;
}
case 11: {
monthAbrev = "Dec";
break;
}
}
return monthAbrev + " " + getYearAsString(i);
}
/** Returns the month, 0=Jan, 1=Feb, etc. */
public int getMonth(int i) {
int ticksPerMonth = ticksPerYear / 12;
return (i % ticksPerYear) / ticksPerMonth;
}
public GameCalendar(int ticksPerYear, int startYear) {
this.ticksPerYear = ticksPerYear;
this.startYear = startYear;
}
@Override
public boolean equals(Object o) {
if (o instanceof GameCalendar) {
GameCalendar test = (GameCalendar) o;
if (this.startYear != test.startYear
|| this.ticksPerYear != test.ticksPerYear) {
return false;
}
return true;
}
return false;
}
public int getTicksPerYear() {
return ticksPerYear;
}
}

ActivityIterator

Full name: jfreerails.world.common.ActivityIterator

Documentation

/**
* This interface provides a bidirectional iterator for traversing a sequence of activities,
* allowing access to their time-related properties and navigation between activities.
* It supports methods to retrieve start and finish times, convert absolute time to relative
* time, and obtain the current activity's state and details.
*
* @see Activity
* @see FreerailsSerializable
*/

Source Code

public interface ActivityIterator {
boolean hasNext();
void nextActivity() throws NoSuchElementException;
/** Returns the time the current activity starts. */
double getStartTime();
/** Returns the time the current activity ends. */
double getFinishTime();
double getDuration();
/**
* Converts an absolute time value to a time value relative to the start of
* the current activity. If absoluteTime > getFinishTime(), getDuration() is
* returned.
*/
double absolute2relativeTime(double absoluteTime);
FreerailsSerializable getState(double absoluteTime);
Activity getActivity();
void gotoLastActivity();
void previousActivity() throws NoSuchElementException;
boolean hasPrevious();
}

FlatTrackTemplate

Full name: jfreerails.world.common.FlatTrackTemplate

Documentation

/**
* Defines methods that encode a track configuration as an int.
*
* @author Luke
*/

Source Code

/**
* Defines methods that encode a track configuration as an int.
*
* @author Luke
*/
public interface FlatTrackTemplate extends FreerailsSerializable {
/**
* @param ftt
* the FlatTrackTemplate which may be a subset of this
* FlatTrackTemplate.
* @return true if the vectors represented by this FlatTrackTemplate are a
* superset of the vectors of the specified FlatTrackTemplate
*/
boolean contains(FlatTrackTemplate ftt);
/**
* @return the integer representing the vector(s) of this object.
*/
int get9bitTemplate();
}

ImHashSet

Full name: jfreerails.world.common.ImHashSet

Documentation

/**
* <p>
* ImHashSet is an immutable wrapper class for a {@link HashSet} that ensures
* the contents cannot be modified after creation. It provides immutability
* guarantees and implements the {@link FreerailsSerializable} interface for
* serialization support.
* </p>
* <p>
* This class delegates all operations to an internal {@link HashSet} instance
* but enforces immutability by making all modifications (such as adding or
* removing elements) unsupported. The iterator returned by {@link #iterator()}
* does not allow removal of elements.
* </p>
*
* @since 1.0
* @see HashSet
* @see FreerailsSerializable
* @see java.util.Iterator
* @see java.util.Set
*/

Source Code

@Immutable
public class ImHashSet<E extends FreerailsSerializable> implements
FreerailsSerializable {
private static final long serialVersionUID = -4098862905501171517L;
private final HashSet<E> hashSet;
public ImHashSet(HashSet<E> hashSet) {
this.hashSet = new HashSet<E>(hashSet);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImHashSet))
return false;
final ImHashSet imHashSet = (ImHashSet) o;
if (!hashSet.equals(imHashSet.hashSet))
return false;
return true;
}
@Override
public int hashCode() {
return hashSet.hashCode();
}
public ImHashSet(E... values) {
this.hashSet = new HashSet<E>();
for (E e : values) {
hashSet.add(e);
}
}
public ImHashSet(List<E> values) {
this.hashSet = new HashSet<E>();
for (E e : values) {
hashSet.add(e);
}
}
public boolean contains(E e) {
return hashSet.contains(e);
}
public Iterator<E> iterator() {
return new Iterator<E>() {
Iterator<E> it = hashSet.iterator();
public boolean hasNext() {
return it.hasNext();
}
public E next() {
return it.next();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}

GameTime

Full name: jfreerails.world.common.GameTime

Documentation

/**
* This class represents a specific instant in time during a game.
*
* @author Luke
*
*/

Source Code

/**
* This class represents a specific instant in time during a game.
*
* @author Luke
*
*/
public class GameTime implements FreerailsSerializable, Comparable<GameTime> {
private static final long serialVersionUID = 3691035461301055541L;
/** The first possible time. */
public static final GameTime BIG_BANG = new GameTime(Integer.MIN_VALUE);
/** The last possible time. */
public static final GameTime END_OF_THE_WORLD = new GameTime(
Integer.MAX_VALUE);
private final int ticks;
@Override
public String toString() {
return "GameTime:" + String.valueOf(ticks);
}
@Override
public int hashCode() {
return ticks;
}
public GameTime(int l) {
this.ticks = l;
}
public GameTime nextTick() {
return new GameTime(ticks + 1);
}
public int getTicks() {
return ticks;
}
@Override
public boolean equals(Object o) {
if (o instanceof GameTime) {
GameTime test = (GameTime) o;
return this.ticks == test.ticks;
}
return false;
}
/**
* Compares two GameTimes for ordering.
*
* @param t
* @return 0 if t is equal to this GameTime; a value less than 0 if this
* GameTime is before t; and a value greater than 0 if this GameTime
* is after t.
*/
public int compareTo(GameTime t) {
return ticks - t.ticks;
}
}

ImStringList

Full name: jfreerails.world.common.ImStringList

Documentation

/**
* An immutable list of Strings.
*
* @author Luke
*
*/

Source Code

/**
* An immutable list of Strings.
*
* @author Luke
*
*/
@Immutable
public class ImStringList implements FreerailsSerializable {
private static final long serialVersionUID = 5211786598838212188L;
private final String[] strings;
public ImStringList(String... strings) {
this.strings = strings.clone();
}
public String get(int i) {
return strings[i];
}
public int size() {
return strings.length;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImStringList))
return false;
final ImStringList imStringList = (ImStringList) o;
if (!Arrays.equals(strings, imStringList.strings))
return false;
return true;
}
@Override
public int hashCode() {
return strings.length;
}
}

GameSpeed

Full name: jfreerails.world.common.GameSpeed

Documentation

/**
* This class represents actual game speed. If the game speed <code>speed</code>
* is lesser then zero, game is paused. After unpausing, the speed should be
* <code>-speed</code>.
*
* I.e. pausing/unpausing is equal to multiply the speed by -1.
*
* @author MystiqueAgent
*
*/

Source Code

/**
* This class represents actual game speed. If the game speed <code>speed</code>
* is lesser then zero, game is paused. After unpausing, the speed should be
* <code>-speed</code>.
*
* I.e. pausing/unpausing is equal to multiply the speed by -1.
*
* @author MystiqueAgent
*
*/
public class GameSpeed implements FreerailsSerializable {
private static final long serialVersionUID = 3257562901983081783L;
private final int speed;
@Override
public String toString() {
return "GameSpeed:" + String.valueOf(speed);
}
public GameSpeed(int speed) {
this.speed = speed;
}
public int getSpeed() {
return speed;
}
public boolean isPaused(){
return speed < 1;
}
@Override
public boolean equals(Object o) {
if (o instanceof GameSpeed) {
GameSpeed test = (GameSpeed) o;
return this.speed == test.speed;
}
return false;
}
@Override
public int hashCode() {
return speed;
}
}

FreerailsSerializable

Full name: jfreerails.world.common.FreerailsSerializable

Documentation

/**
* This interface tags classes that can be sent between the client and the
* server.
*
* <b>
* <p>
* Every class that implements this interface should be immutable. </b>
*
* @author Luke
*/

Source Code

/**
* This interface tags classes that can be sent between the client and the
* server.
*
* <b>
* <p>
* Every class that implements this interface should be immutable. </b>
*
* @author Luke
*/
public interface FreerailsSerializable extends Serializable {
}

Methods

No methods found

ImPoint

Full name: jfreerails.world.common.ImPoint

Documentation

/**
* An immutable point.
*
* @author Luke
*
*/

Source Code

/**
* An immutable point.
*
* @author Luke
*
*/
@Immutable
public final class ImPoint implements FreerailsSerializable, Comparable<ImPoint> {
private static final long serialVersionUID = -3053020239886388576L;
public final int x, y;
public ImPoint() {
x = 0;
y = 0;
}
public ImPoint(Point p) {
x = p.x;
y = p.y;
}
public ImPoint(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImPoint))
return false;
final ImPoint imPoint = (ImPoint) o;
if (x != imPoint.x)
return false;
if (y != imPoint.y)
return false;
return true;
}
public Point toPoint() {
return new Point(x, y);
}
@Override
public int hashCode() {
return x * 1000 + y;
}
@Override
public String toString() {
return "ImPoint{" + x + ", " + y + "}";
}
public int compareTo(ImPoint o) {
if (o.y != y)
return y - o.y;
else
return x - o.x;
}
}

PlayerPrincipal

Full name: jfreerails.world.player.PlayerPrincipal

Documentation

/**
* FreerailsPrincipal that is a player in the game.
*
* @author rob
*/

Source Code

/**
* FreerailsPrincipal that is a player in the game.
*
* @author rob
*/
public class PlayerPrincipal extends FreerailsPrincipal {
private static final long serialVersionUID = 3257563997099537459L;
private final int id;
private final String name;
public PlayerPrincipal(int id, String name) {
super(id);
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
@Override
public int hashCode() {
return id;
}
@Override
public String toString() {
return "Player " + id;
}
/**
* @return an integer unique to this PlayerPrincipal
*/
public int getId() {
return id;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof PlayerPrincipal)) {
return false;
}
return id == ((PlayerPrincipal) o).id;
}
}

Player

Full name: jfreerails.world.player.Player

Documentation

/**
* Represents a player within the game. The player model is such that a user can
* start a client, create a new player on the server and start playing. They can
* disconnect from the server, which may continue running with other players
* still active. The server can then save the list of players and be stopped and
* restarted again, the clients can then authenticate themselves to the server
* and continue their sessions where they left off.
*
* XXX the player is only authenticated when the connection is opened, and
* subsequent exchanges are not authenticated.
*
* TODO implement a more complete authentication system using certificates
* rather than public keys.
*
* @author rtuck99@users.sourceforge.net
*/

Source Code

/**
* Represents a player within the game. The player model is such that a user can
* start a client, create a new player on the server and start playing. They can
* disconnect from the server, which may continue running with other players
* still active. The server can then save the list of players and be stopped and
* restarted again, the clients can then authenticate themselves to the server
* and continue their sessions where they left off.
*
* XXX the player is only authenticated when the connection is opened, and
* subsequent exchanges are not authenticated.
*
* TODO implement a more complete authentication system using certificates
* rather than public keys.
*
* @author rtuck99@users.sourceforge.net
*/
public class Player implements FreerailsSerializable {
private static final long serialVersionUID = 1;
/** A FreerailsPrincipal that is not a player. */
private static class WorldPrincipal extends FreerailsPrincipal {
private static final long serialVersionUID = 1;
private final String principalName;
public WorldPrincipal(String name) {
super(-1);
this.principalName = name;
}
public String getName() {
return principalName;
}
@Override
public String toString() {
return principalName;
}
@Override
public int hashCode() {
return principalName.hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof WorldPrincipal)) {
return false;
}
return (principalName.equals(((WorldPrincipal) o).principalName));
}
}
private FreerailsPrincipal principal;
/**
* This Principal can be granted all permissions.
*/
public static final FreerailsPrincipal AUTHORITATIVE = new WorldPrincipal(
"Authoritative Server");
/**
* This Principal has no permissions.
*/
public static final FreerailsPrincipal NOBODY = new WorldPrincipal("Nobody");
/**
* Name of the player.
*/
private final String name;
/**
* Used by the client to generate a player with a particular name.
*/
public Player(String name) {
this.name = name;
KeyPairGenerator kpg;
/* generate our key pair */
try {
kpg = KeyPairGenerator.getInstance("DSA");
kpg.initialize(1024);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
/**
* Used by the server to generate a player with a particular name and public
* key.
*
*/
public Player(String name, int id) {
this.name = name;
// this.publicKey = publicKey;
// privateData = new PrivateData();
this.principal = new PlayerPrincipal(id, name);
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (!(o instanceof Player)) {
return false;
}
// return (name.equals(((Player) o).name) && keysEqual);
return (name.equals(((Player) o).name));
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public String toString() {
return name;
}
public String getName() {
return name;
}
/**
* TODO save this player's private data so that they can be re-connected to
* the server at a later point in time.
*/
public void saveSession(ObjectOutputStream out) throws IOException {
// out.writeObject(privateData);
}
/**
* Called by the client to reconstitute the data from a saved game.
*/
public void loadSession(ObjectInputStream in) throws IOException {
// try {
// privateData = (PrivateData) in.readObject();
// } catch (ClassNotFoundException e) {
// throw new IOException("Couldn't find class:" + e);
// }
}
public FreerailsPrincipal getPrincipal() {
return principal;
}
}

FreerailsPrincipal

Full name: jfreerails.world.player.FreerailsPrincipal

Documentation

/**
* This interface identifies a principal. This interface may be extended in the
* future in order to provide faster lookups, rather than using name
* comparisons.
*
* A principal represents an entity which can view or alter the game world. A
* principal usually corresponds to a player's identity, but may also represent
* an authoritative server, or a another game entity such as a corporation.
* All entities which may own game world objects must be represented by a
* principal.
*
* @author rob
*/

Source Code

/**
* This interface identifies a principal. This interface may be extended in the
* future in order to provide faster lookups, rather than using name
* comparisons.
*
* A principal represents an entity which can view or alter the game world. A
* principal usually corresponds to a player's identity, but may also represent
* an authoritative server, or a another game entity such as a corporation.
* All entities which may own game world objects must be represented by a
* principal.
*
* @author rob
*/
public abstract class FreerailsPrincipal implements Principal,
FreerailsSerializable {
private static final long serialVersionUID = -1689464560504992959L;
private int worldIndex;
public FreerailsPrincipal(int worldIndex) {
this.worldIndex = worldIndex;
}
/**
* returns -1 if it's not a player
* @return the index in the world structures
*/
public int getWorldIndex() {
return worldIndex;
}
}

Demand4Cargo

Full name: jfreerails.world.station.Demand4Cargo

Documentation

/**
* This class represents the demand for cargo at a station.
*
* @author Luke
*/

Source Code

/**
* This class represents the demand for cargo at a station.
*
* @author Luke
*/
public class Demand4Cargo implements FreerailsSerializable {
private static final long serialVersionUID = 3257565088071038009L;
private final ImInts demand;
public Demand4Cargo(boolean[] demandArray) {
demand = ImInts.fromBoolean(demandArray);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Demand4Cargo))
return false;
final Demand4Cargo demandAtStation = (Demand4Cargo) o;
if (!demand.equals(demandAtStation.demand))
return false;
return true;
}
@Override
public int hashCode() {
int result = 0;
for (int i = 0; i < demand.size(); i++) {
result = 29 * result + demand.get(i);
}
return result;
}
public boolean isCargoDemanded(int cargoNumber) {
return demand.get(cargoNumber) == 1;
}
}

PlannedTrain

Full name: jfreerails.world.station.PlannedTrain

Documentation

/**
* This class represents the blue print for what an engine shop is producing.
*
* @author Luke
*
*/

Source Code

/**
* This class represents the blue print for what an engine shop is producing.
*
* @author Luke
*
*/
public class PlannedTrain implements FreerailsSerializable {
private static final long serialVersionUID = 3545515106038592057L;
private final int engineType;
private final ImInts wagonTypes;
public PlannedTrain(int e, int[] wagons) {
engineType = e;
wagonTypes = new ImInts(wagons);
}
@Override
public int hashCode() {
return engineType;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof PlannedTrain))
return false;
final PlannedTrain productionAtEngineShop = (PlannedTrain) o;
if (engineType != productionAtEngineShop.engineType)
return false;
if (!wagonTypes.equals(productionAtEngineShop.wagonTypes))
return false;
return true;
}
public int getEngineType() {
return engineType;
}
public ImInts getWagonTypes() {
return wagonTypes;
}
@Override
public String toString() {
return "engine type: " + this.engineType + ", with "
+ wagonTypes.size() + "wagons";
}
}

ConvertedAtStation

Full name: jfreerails.world.station.ConvertedAtStation

Documentation

/**
* Records which cargos are converted to other cargos at a station.
*
* @author Luke
*/

Source Code

/**
* Records which cargos are converted to other cargos at a station.
*
* @author Luke
*/
public class ConvertedAtStation implements FreerailsSerializable {
private static final long serialVersionUID = 3690754012076978231L;
private static final int NOT_CONVERTED = Integer.MIN_VALUE;
private final ImInts convertedTo;
public ConvertedAtStation(int[] convertedTo) {
this.convertedTo = new ImInts(convertedTo);
}
public static ConvertedAtStation emptyInstance(int numberOfCargoTypes) {
int[] convertedTo = emptyConversionArray(numberOfCargoTypes);
return new ConvertedAtStation(convertedTo);
}
public static int[] emptyConversionArray(int numberOfCargoTypes) {
int[] convertedTo = new int[numberOfCargoTypes];
for (int i = 0; i < numberOfCargoTypes; i++) {
convertedTo[i] = NOT_CONVERTED;
}
return convertedTo;
}
public boolean isCargoConverted(int cargoNumber) {
if (NOT_CONVERTED == convertedTo.get(cargoNumber)) {
return false;
}
return true;
}
public int getConversion(int cargoNumber) {
return convertedTo.get(cargoNumber);
}
@Override
public int hashCode() {
int result = 0;
for (int i = 0; i < convertedTo.size(); i++) {
result = 29 * result + convertedTo.get(i);
}
return result;
}
@Override
public boolean equals(Object o) {
if (o instanceof ConvertedAtStation) {
ConvertedAtStation test = (ConvertedAtStation) o;
if (this.convertedTo.size() != test.convertedTo.size()) {
return false;
}
for (int i = 0; i < convertedTo.size(); i++) {
if (convertedTo.get(i) != test.convertedTo.get(i)) {
return false;
}
}
return true;
}
return false;
}
}

StationModel

Full name: jfreerails.world.station.StationModel

Documentation

/**
* This class represents a station.
*
* @author Luke
*
*/

Source Code

/**
* This class represents a station.
*
* @author Luke
*
*/
public class StationModel implements FreerailsSerializable {
private static final long serialVersionUID = 3256442503979874355L;
public final int x;
public final int y;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof StationModel))
return false;
final StationModel stationModel = (StationModel) o;
if (cargoBundleNumber != stationModel.cargoBundleNumber)
return false;
if (x != stationModel.x)
return false;
if (y != stationModel.y)
return false;
if (converted != null ? !converted.equals(stationModel.converted)
: stationModel.converted != null)
return false;
if (demand != null ? !demand.equals(stationModel.demand)
: stationModel.demand != null)
return false;
if (!name.equals(stationModel.name))
return false;
if (production != null ? !production.equals(stationModel.production)
: stationModel.production != null)
return false;
if (supply != null ? !supply.equals(stationModel.supply)
: stationModel.supply != null)
return false;
return true;
}
private final String name;
private final SupplyAtStation supply;
private final Demand4Cargo demand;
private final ConvertedAtStation converted;
private final int cargoBundleNumber;
/** What this station is building. */
private final ImList<PlannedTrain> production;
public ConvertedAtStation getConverted() {
return converted;
}
@Override
public int hashCode() {
int result;
result = x;
result = 29 * result + y;
result = 29 * result + (name != null ? name.hashCode() : 0);
result = 29 * result + (supply != null ? supply.hashCode() : 0);
result = 29 * result + (demand != null ? demand.hashCode() : 0);
result = 29 * result + (converted != null ? converted.hashCode() : 0);
result = 29 * result + cargoBundleNumber;
result = 29 * result + production.size();
return result;
}
public StationModel(StationModel s, ConvertedAtStation converted) {
this.converted = converted;
this.cargoBundleNumber = s.cargoBundleNumber;
this.demand = s.demand;
this.name = s.name;
this.production = s.production;
this.supply = s.supply;
this.x = s.x;
this.y = s.y;
}
public StationModel(int x, int y, String stationName,
int numberOfCargoTypes, int cargoBundle) {
this.name = stationName;
this.x = x;
this.y = y;
production = new ImList<PlannedTrain>();
supply = new SupplyAtStation(new int[numberOfCargoTypes]);
demand = new Demand4Cargo(new boolean[numberOfCargoTypes]);
converted = ConvertedAtStation.emptyInstance(numberOfCargoTypes);
cargoBundleNumber = cargoBundle;
}
public StationModel() {
this.name = "No name";
x = 0;
y = 0;
this.demand = new Demand4Cargo(new boolean[0]);
this.supply = new SupplyAtStation(new int[0]);
this.converted = new ConvertedAtStation(new int[0]);
production = new ImList<PlannedTrain>();
this.cargoBundleNumber = 0;
}
public String getStationName() {
return name;
}
public int getStationX() {
return x;
}
public int getStationY() {
return y;
}
public ImPoint getLocation(){
return new ImPoint(x, y);
}
public ImList<PlannedTrain> getProduction() {
return production;
}
public StationModel(StationModel s, ImList<PlannedTrain> production) {
this.production = production;
this.demand = s.demand;
this.cargoBundleNumber = s.cargoBundleNumber;
this.converted = s.converted;
this.name = s.name;
this.supply = s.supply;
this.x = s.x;
this.y = s.y;
}
public Demand4Cargo getDemand() {
return demand;
}
public SupplyAtStation getSupply() {
return supply;
}
public StationModel(StationModel s, Demand4Cargo demand) {
this.demand = demand;
this.cargoBundleNumber = s.cargoBundleNumber;
this.converted = s.converted;
this.name = s.name;
this.production = s.production;
this.supply = s.supply;
this.x = s.x;
this.y = s.y;
}
public StationModel(StationModel s, SupplyAtStation supply) {
this.supply = supply;
this.demand = s.demand;
this.cargoBundleNumber = s.cargoBundleNumber;
this.converted = s.converted;
this.name = s.name;
this.production = s.production;
this.x = s.x;
this.y = s.y;
}
public int getCargoBundleID() {
return cargoBundleNumber;
}
}

SupplyAtStation

Full name: jfreerails.world.station.SupplyAtStation

Documentation

/**
* This class represents the supply at a station.
*
* @author Luke
*/

Source Code

/**
* This class represents the supply at a station.
*
* @author Luke
*/
public class SupplyAtStation implements FreerailsSerializable {
private static final long serialVersionUID = 4049918272826847286L;
private final ImInts supply;
public SupplyAtStation(int[] cargoWaiting) {
supply = new ImInts(cargoWaiting);
}
/**
* Returns the number of car loads of the specified cargo that the station
* supplies per year.
*/
public int getSupply(int cargoType) {
return supply.get(cargoType);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof SupplyAtStation))
return false;
final SupplyAtStation supplyAtStation = (SupplyAtStation) o;
if (!supply.equals(supplyAtStation.supply))
return false;
return true;
}
@Override
public int hashCode() {
return supply.hashCode();
}
}

TerrainType

Full name: jfreerails.world.terrain.TerrainType

Documentation

/**
* Defines the methods to access the properties of a type of terrains.
*
*
* @author Luke
*/

Source Code

/**
* Defines the methods to access the properties of a type of terrains.
*
*
* @author Luke
*/
public interface TerrainType extends FreerailsSerializable {
enum Category implements FreerailsSerializable {
Urban, River, Ocean, Hill, Country, Special, Industry, Resource
}
String getTerrainTypeName();
Category getCategory();
Money getBuildCost();
int getRightOfWay();
int getRGB();
ImList<Production> getProduction();
ImList<Consumption> getConsumption();
ImList<Conversion> getConversion();
String getDisplayName();
}

NullTerrainType

Full name: jfreerails.world.terrain.NullTerrainType

Documentation

/**
* Represents a null terrain type, serving as a default or placeholder implementation.
* This singleton class provides empty or default values for all terrain type properties,
* ensuring compatibility with the TerrainType interface when no specific terrain type is applicable.
*
* @author Your Name
* @see TerrainType
*/

Source Code

@InstanceControlled
public class NullTerrainType implements TerrainType {
public static final TerrainType INSTANCE = new NullTerrainType();
private NullTerrainType() {
}
private static final long serialVersionUID = 3834874680581369912L;
public ImList<Production> getProduction() {
return new ImList<Production>();
}
public ImList<Consumption> getConsumption() {
return new ImList<Consumption>();
}
public ImList<Conversion> getConversion() {
return new ImList<Conversion>();
}
public String getTerrainTypeName() {
return "null";
}
public Category getCategory() {
return Category.Country;
}
public int getRGB() {
return 0;
}
public int getRightOfWay() {
return 0;
}
public String getDisplayName() {
return "";
}
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
public Money getBuildCost() {
return new Money(0);
}
}

CityModel

Full name: jfreerails.world.terrain.CityModel

Documentation

/**
* A city.
*
* @author Luke
*/

Source Code

/**
* A city.
*
* @author Luke
*/
public class CityModel implements FreerailsSerializable {
private static final long serialVersionUID = 3256720697500709428L;
private final String name;
private final int x;
private final int y;
public CityModel(String s, int xx, int yy) {
name = s;
x = xx;
y = yy;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof CityModel))
return false;
final CityModel cityModel = (CityModel) o;
if (x != cityModel.x)
return false;
if (y != cityModel.y)
return false;
if (!name.equals(cityModel.name))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = name.hashCode();
result = 29 * result + x;
result = 29 * result + y;
return result;
}
public String getCityName() {
return name;
}
public int getCityX() {
return x;
}
public int getCityY() {
return y;
}
public ImPoint getLocation(){
return new ImPoint(x, y);
}
@Override
public String toString() {
return name+" "+x+", "+y;
}
}

TerrainTile

Full name: jfreerails.world.terrain.TerrainTile

Documentation

/**
* Defines the interface of a terrain tile.
*
* @author Luke
*/

Source Code

/**
* Defines the interface of a terrain tile.
*
* @author Luke
*/
public interface TerrainTile extends FreerailsSerializable {
int getTerrainTypeID();
}

Consumption

Full name: jfreerails.world.terrain.Consumption

Documentation

/**
* This class represents the demand for a certain cargo for consumption.
*
* @author Luke
*
*/

Source Code

/**
* This class represents the demand for a certain cargo for consumption.
*
* @author Luke
*
*/
public class Consumption implements FreerailsSerializable {
private static final long serialVersionUID = 3258133565631051064L;
private final int cargoType;
/**
* The number of tiles that must be within the station radius before the
* station demands the cargo.
*/
private final int prerequisite;
public Consumption(int ct, int pq) {
cargoType = ct;
prerequisite = pq; // default value.
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Consumption))
return false;
final Consumption consumption = (Consumption) o;
if (cargoType != consumption.cargoType)
return false;
if (prerequisite != consumption.prerequisite)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = cargoType;
result = 29 * result + prerequisite;
return result;
}
public int getCargoType() {
return cargoType;
}
public int getPrerequisite() {
return prerequisite;
}
}

Conversion

Full name: jfreerails.world.terrain.Conversion

Documentation

/**
* This class represents the conversion of one cargo type to another one a tile.
*
* @author Luke
*
*/

Source Code

/**
* This class represents the conversion of one cargo type to another one a tile.
*
* @author Luke
*
*/
public class Conversion implements FreerailsSerializable {
private static final long serialVersionUID = 3546356219414853689L;
private final int input;
private final int output;
public Conversion(int in, int out) {
input = in;
output = out;
}
public int getInput() {
return input;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Conversion))
return false;
final Conversion conversion = (Conversion) o;
if (input != conversion.input)
return false;
if (output != conversion.output)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = input;
result = 29 * result + output;
return result;
}
public int getOutput() {
return output;
}
}

Production

Full name: jfreerails.world.terrain.Production

Documentation

/**
* This class represents the production of a raw material on a tile.
*
* @author Luke
*
*/

Source Code

/**
* This class represents the production of a raw material on a tile.
*
* @author Luke
*
*/
public class Production implements FreerailsSerializable {
private static final long serialVersionUID = 3258125847641536052L;
private final int cargoType;
/** The number of units per year (40 units = 1 car load). */
private final int rate;
public Production(int type, int r) {
cargoType = type;
rate = r;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Production))
return false;
final Production production = (Production) o;
if (cargoType != production.cargoType)
return false;
if (rate != production.rate)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = cargoType;
result = 29 * result + rate;
return result;
}
public int getCargoType() {
return cargoType;
}
public int getRate() {
return rate;
}
}

TileTypeImpl

Full name: jfreerails.world.terrain.TileTypeImpl

Documentation

/**
* Represents a type of terrain.
*
* @author Luke Lindsay 16 August 2001
*/

Source Code

/**
* Represents a type of terrain.
*
* @author Luke Lindsay 16 August 2001
*/
final public class TileTypeImpl implements TerrainType {
private static final long serialVersionUID = 4049919380945253945L;
private final ImList<Consumption> consumption;
private final ImList<Conversion> conversion;
private final ImList<Production> production;
private final int rgb;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TileTypeImpl))
return false;
final TileTypeImpl tileType = (TileTypeImpl) o;
if (rgb != tileType.rgb)
return false;
if (rightOfWay != tileType.rightOfWay)
return false;
if (!consumption.equals(tileType.consumption))
return false;
if (!conversion.equals(tileType.conversion))
return false;
if (!production.equals(tileType.production))
return false;
if (!terrainCategory.equals(tileType.terrainCategory))
return false;
if (!terrainType.equals(tileType.terrainType))
return false;
if (tileBuildCost != null ? !tileBuildCost
.equals(tileType.tileBuildCost)
: tileType.tileBuildCost != null)
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = consumption.hashCode();
result = 29 * result + conversion.hashCode();
result = 29 * result + production.hashCode();
result = 29 * result + rgb;
result = 29 * result + rightOfWay;
result = 29 * result + terrainCategory.hashCode();
result = 29 * result + terrainType.hashCode();
result = 29 * result
+ (tileBuildCost != null ? tileBuildCost.hashCode() : 0);
return result;
}
private final int rightOfWay;
private final TerrainType.Category terrainCategory;
private final String terrainType;
/**
* Cost to build a tile of this terrain type or null if this type is not
* buildable.
*/
private final Money tileBuildCost;
public TileTypeImpl(int rgb, TerrainType.Category terrainCategory,
String terrainType, int rightOfWay, Production[] production,
Consumption[] consumption, Conversion[] conversion,
int tileBuildCost) {
this.terrainType = terrainType;
this.terrainCategory = terrainCategory;
this.rgb = rgb;
this.rightOfWay = rightOfWay;
this.production = new ImList<Production>(production);
this.consumption = new ImList<Consumption>(consumption);
this.conversion = new ImList<Conversion>(conversion);
if (tileBuildCost > 0) {
this.tileBuildCost = new Money(tileBuildCost);
} else {
this.tileBuildCost = null;
}
}
/**
* Lets unit tests create terrain types without bothering with all the
* details.
*/
public TileTypeImpl(TerrainType.Category terrainCategory, String terrainType) {
this.terrainType = terrainType;
this.terrainCategory = terrainCategory;
this.rgb = 0;
this.rightOfWay = 0;
this.production = new ImList<Production>();
this.consumption = new ImList<Consumption>();
this.conversion = new ImList<Conversion>();
this.tileBuildCost = null;
}
public Money getBuildCost() {
return tileBuildCost;
}
public Category getCategory() {
return terrainCategory;
}
public ImList<Consumption> getConsumption() {
return consumption;
}
public ImList<Conversion> getConversion() {
return conversion;
}
/** Returns the name, replacing any underscores with spaces. */
public String getDisplayName() {
return terrainType.replace('_', ' ');
}
public ImList<Production> getProduction() {
return production;
}
/**
* @return The RGB value mapped to this terrain type.
*/
public int getRGB() {
return rgb;
}
public int getRightOfWay() {
return rightOfWay;
}
public String getTerrainTypeName() {
return terrainType;
}
}

BondTransaction

Full name: jfreerails.world.accounts.BondTransaction

Documentation

/**
* A Transaction that adds or removes a Bond.
*
* @author Luke
*
*/

Source Code

/**
* A Transaction that adds or removes a Bond.
*
* @author Luke
*
*/
public class BondTransaction extends AddItemTransaction {
private static final long serialVersionUID = 3257562923491473465L;
public static final Money BOND_VALUE_ISSUE = new Money(500000);
public static final Money BOND_VALUE_REPAY = new Money(-500000);
private BondTransaction(Category category, int type, int quantity,
Money amount) {
super(category, type, quantity, amount);
}
public static BondTransaction issueBond(int interestRate) {
return new BondTransaction(Category.BOND, interestRate, 1,
BOND_VALUE_ISSUE);
}
public static BondTransaction repayBond(int interestRate) {
return new BondTransaction(Category.BOND, interestRate, -1,
BOND_VALUE_REPAY);
}
}

Receipt

Full name: jfreerails.world.accounts.Receipt

Documentation

/**
* A credit.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* A credit.
*
* @author Luke Lindsay
*
*/
public class Receipt implements Transaction {
private static final long serialVersionUID = 3617576007066924596L;
private final Money amount;
private final Category category;
public Receipt(Money m, Category category) {
this.amount = m;
this.category = category;
}
public Money deltaAssets() {
return amount.changeSign();
}
public Money deltaCash() {
return amount;
}
@Override
public boolean equals(Object o) {
if (o instanceof Receipt) {
Receipt test = (Receipt) o;
return test.amount.equals(amount) && category == test.category;
}
return false;
}
public Category getCategory() {
return category;
}
@Override
public int hashCode() {
int result;
result = amount.hashCode();
result = 29 * result + category.hashCode();
return result;
}
}

AddItemTransaction

Full name: jfreerails.world.accounts.AddItemTransaction

Documentation

/**
* This Transaction represents the charge/credit for buying/selling an item.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* This Transaction represents the charge/credit for buying/selling an item.
*
* @author Luke Lindsay
*
*/
public class AddItemTransaction implements Transaction {
private static final long serialVersionUID = 3690471411852326457L;
private final Money amount;
/** For example track. */
private final Category category;
/** For example, 4 tiles. */
private final int quantity;
/** For example, standard track. */
private final int type;
public AddItemTransaction(Category category, int type, int quantity,
Money amount) {
this.category = category;
this.type = type;
this.quantity = quantity;
this.amount = amount;
}
public Money deltaAssets() {
return amount.changeSign();
}
public Money deltaCash() {
return amount;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AddItemTransaction) {
AddItemTransaction test = (AddItemTransaction) obj;
return this.amount.equals(test.amount) && category == test.category
&& type == test.type && quantity == test.quantity;
}
return false;
}
public Category getCategory() {
return category;
}
public int getQuantity() {
return quantity;
}
public int getType() {
return type;
}
@Override
public int hashCode() {
int result;
result = category.hashCode();
result = 29 * result + type;
result = 29 * result + quantity;
result = 29 * result + amount.hashCode();
return result;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("AddItemTransaction ");
sb.append(category);
sb.append(", type ");
sb.append(type);
sb.append(", quantity ");
sb.append(quantity);
sb.append(", amount ");
sb.append(amount);
return sb.toString();
}
}

EconomicClimate

Full name: jfreerails.world.accounts.EconomicClimate

Documentation

/**
* Represents the state of the economy.
*
* @author Luke
*
*/

Source Code

/**
* Represents the state of the economy.
*
* @author Luke
*
*/
public class EconomicClimate implements FreerailsSerializable {
private static final long serialVersionUID = 3834025840475321136L;
private static int i = 2;
private final String name;
public static final EconomicClimate BOOM = new EconomicClimate(i++, "BOOM");
public static final EconomicClimate PROSPERITY = new EconomicClimate(i++,
"PROSPERITY");
public static final EconomicClimate MODERATION = new EconomicClimate(i++,
"MODERATION");
public static final EconomicClimate RECESSION = new EconomicClimate(i++,
"RECESSION");
public static final EconomicClimate PANIC = new EconomicClimate(i++,
"PANIC");
public int getBaseInterestRate() {
return baseInterestRate;
}
private final int baseInterestRate;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof EconomicClimate)) {
return false;
}
final EconomicClimate economicClimate = (EconomicClimate) o;
if (baseInterestRate != economicClimate.baseInterestRate) {
return false;
}
if (name != null ? !name.equals(economicClimate.name)
: economicClimate.name != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result;
result = (name != null ? name.hashCode() : 0);
result = 29 * result + baseInterestRate;
return result;
}
private EconomicClimate(int r, String s) {
baseInterestRate = r;
name = s;
}
}

TransactionAndTimeStamp

Full name: jfreerails.world.accounts.TransactionAndTimeStamp

Documentation

/**
* Represents a pair of a transaction and a timestamp, used to track when a transaction occurred in a game context.
* This class encapsulates a {@link Transaction} object and a {@link GameTime} object, providing immutable access to both.
* It implements {@link FreerailsSerializable} to support serialization for saving game states or transmitting data.
*
* @see Transaction
* @see GameTime
* @see FreerailsSerializable
*/

Source Code

public class TransactionAndTimeStamp implements FreerailsSerializable {
private static final long serialVersionUID = 1540065347606694456L;
private final Transaction t;
private final GameTime timeStamp;
public TransactionAndTimeStamp(Transaction t, GameTime stamp) {
this.t = t;
timeStamp = stamp;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TransactionAndTimeStamp))
return false;
final TransactionAndTimeStamp transactionAndTimeStamp = (TransactionAndTimeStamp) o;
if (!t.equals(transactionAndTimeStamp.t))
return false;
if (!timeStamp.equals(transactionAndTimeStamp.timeStamp))
return false;
return true;
}
@Override
public int hashCode() {
int result;
result = t.hashCode();
result = 29 * result + timeStamp.hashCode();
return result;
}
public Transaction getT() {
return t;
}
public GameTime getTimeStamp() {
return timeStamp;
}
}

StockTransaction

Full name: jfreerails.world.accounts.StockTransaction

Documentation

/**
* A transaction that occurs when a new company is founded or when a company
* issues additional shares.
*
* @author Luke
* @author smackay
*/

Source Code

/**
* A transaction that occurs when a new company is founded or when a company
* issues additional shares.
*
* @author Luke
* @author smackay
*/
public class StockTransaction extends AddItemTransaction {
private static final long serialVersionUID = 3256441412924224824L;
public static final int STOCK_BUNDLE_SIZE = 10000;
private StockTransaction(Category category, int playerId, int quantity,
Money amount) {
super(category, playerId, quantity, amount);
if (playerId < 0)
throw new IllegalArgumentException();
}
public static StockTransaction issueStock(int playerId, int quantity,
Money pricePerShare) {
// Issue Stock of the Player
long temp = (pricePerShare.getAmount() * quantity);
temp = temp - temp - temp;
Money amount = new Money(temp).changeSign();
return new StockTransaction(Transaction.Category.ISSUE_STOCK, playerId,
quantity, amount);
}
public static StockTransaction buyOrSellStock(int playerId, int quantity,
Money stockPrice) {
// Buys another Players Stock, Uses another Category
Money value = new Money(stockPrice.getAmount() * quantity * -1);
return new StockTransaction(Transaction.Category.TRANSFER_STOCK,
playerId, quantity, value);
}
public static StockTransaction issueStock(int quantity, long pricePerShare) {
Money amount = new Money(pricePerShare * quantity);
return new StockTransaction(quantity, amount);
}
private StockTransaction(int quantity, Money amount) {
super(Transaction.Category.ISSUE_STOCK, -1, quantity, amount);
}
}

Transaction

Full name: jfreerails.world.accounts.Transaction

Documentation

/**
* A Transaction is a change in a player's bank balance and/or assets.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* A Transaction is a change in a player's bank balance and/or assets.
*
* @author Luke Lindsay
*
*/
public interface Transaction extends FreerailsSerializable {
public enum Category {
BOND, BRIDGES, CARGO_DELIVERY, INDUSTRIES, INTEREST_CHARGE, ISSUE_STOCK, MISC_INCOME, STATION_MAINTENANCE, STATIONS, TRACK, TRACK_MAINTENANCE, TRAIN, TRAIN_MAINTENANCE, TRANSFER_STOCK
}
Money deltaAssets();
/** Positive means credit. */
Money deltaCash();
Category getCategory();
}

Bill

Full name: jfreerails.world.accounts.Bill

Documentation

/**
* For example, the cost of buying a trains.
*
* @author Luke Lindsay
*
*/

Source Code

/**
* For example, the cost of buying a trains.
*
* @author Luke Lindsay
*
*/
public class Bill implements Transaction {
private static final long serialVersionUID = 3258416144497782835L;
private final Money amount;
private final Category category;
public Bill(Money amount, Category category) {
this.amount = new Money(-amount.getAmount());
this.category = category;
}
public Money deltaAssets() {
return amount.changeSign();
}
public Money deltaCash() {
return amount;
}
@Override
public boolean equals(Object o) {
if (o instanceof Bill) {
Bill test = (Bill) o;
return test.amount.equals(amount) && category == test.category;
}
return false;
}
public Category getCategory() {
return category;
}
@Override
public int hashCode() {
int result;
result = amount.hashCode();
result = 29 * result + category.hashCode();
return result;
}
}

DeliverCargoReceipt

Full name: jfreerails.world.accounts.DeliverCargoReceipt

Documentation

/**
* A credit for delivering cargo.
*
* @author Luke
*
*/

Source Code

/**
* A credit for delivering cargo.
*
* @author Luke
*
*/
public class DeliverCargoReceipt extends Receipt {
private static final long serialVersionUID = 3257009851963160372L;
private final CargoBatch cb;
private final int quantity;
private final int stationId;
private final int trainId;
public DeliverCargoReceipt(Money m, int quantity, int stationId,
CargoBatch cb, int trainId) {
super(m, Category.CARGO_DELIVERY);
this.stationId = stationId;
this.quantity = quantity;
this.cb = cb;
this.trainId = trainId;
}
public int getTrainId() {
return trainId;
}
public CargoBatch getCb() {
return cb;
}
public int getQuantity() {
return quantity;
}
public int getStationId() {
return stationId;
}
}

GameLoop

Full name: jfreerails.client.top.GameLoop

Documentation

/**
* This thread updates the GUI Client window.
*
* @author Luke
*/

Source Code

/**
* This thread updates the GUI Client window.
*
* @author Luke
*/
final public class GameLoop implements Runnable {
private static final Logger logger = Logger.getLogger(GameLoop.class
.getName());
private final static boolean LIMIT_FRAME_RATE = false;
private boolean gameNotDone = false;
private final ScreenHandler screenHandler;
private final static int TARGET_FPS = 40;
private FPScounter fPScounter;
private long frameStartTime;
private final GameModel[] model;
private final Integer loopMonitor = new Integer(0);
public GameLoop(ScreenHandler s) {
screenHandler = s;
model = new GameModel[0];
}
public GameLoop(ScreenHandler s, GameModel[] gm) {
screenHandler = s;
model = gm;
if (null == model) {
throw new NullPointerException();
}
}
public void run() {
try {
SynchronizedEventQueue.use();
RepaintManagerForActiveRendering.addJFrame(screenHandler.frame);
RepaintManagerForActiveRendering.setAsCurrentManager();
if (!screenHandler.isInUse()) {
screenHandler.apply();
}
gameNotDone = true;
fPScounter = new FPScounter();
/*
* Reduce this threads priority to avoid starvation of the input
* thread on Windows.
*/
try {
Thread.currentThread().setPriority(Thread.NORM_PRIORITY - 1);
} catch (SecurityException e) {
logger.warning("Couldn't lower priority of redraw thread");
}
while (true) {
// stats.record();
frameStartTime = System.currentTimeMillis();
/*
* Flush all redraws in the underlying toolkit. This reduces X11
* lag when there isn't much happening, but is expensive under
* Windows
*/
Toolkit.getDefaultToolkit().sync();
synchronized (SynchronizedEventQueue.MUTEX) {
if (!gameNotDone) {
SynchronizedEventQueue.MUTEX.notify();
break;
}
for (int i = 0; i < model.length; i++) {
model[i].update();
}
if (!screenHandler.isMinimised()) {
if (screenHandler.isInUse()) {
boolean contentsRestored = false;
do {
Graphics g = screenHandler.getDrawGraphics();
try {
screenHandler.frame.paintComponents(g);
boolean showFps = Boolean
.parseBoolean(System
.getProperty("SHOWFPS"));
if (showFps) {
fPScounter.drawFPS((Graphics2D) g);
}
} catch (RuntimeException re) {
/*
* We are not expecting a RuntimeException
* here. If something goes wrong, lets kill
* the game straight away to avoid
* hard-to-track-down bugs.
*/
ReportBugTextGenerator
.unexpectedException(re);
} finally {
g.dispose();
}
contentsRestored = screenHandler
.contentsRestored();
} while (contentsRestored);
screenHandler.swapScreens();
fPScounter.updateFPSCounter();
}
}
}
if (screenHandler.isMinimised()) {
try {
// The window is minimised so we don't need to keep
// updating.
Thread.sleep(200);
} catch (Exception e) {
// do nothing.
}
} else if (LIMIT_FRAME_RATE) {
long deltatime = System.currentTimeMillis()
- frameStartTime;
while (deltatime < (1000 / TARGET_FPS)) {
try {
long sleeptime = (1000 / TARGET_FPS) - deltatime;
Thread.sleep(sleeptime);
} catch (Exception e) {
e.printStackTrace();
}
deltatime = System.currentTimeMillis() - frameStartTime;
}
}
// remove all events from a event queue (max 5ms)
long startEventWaitTime = System.currentTimeMillis() + 4;
while (SynchronizedEventQueue.getInstance().peekEvent() != null) {
// we have events
Thread.yield();
if (startEventWaitTime < System.currentTimeMillis()) {
break;
}
}
}
/* signal that we are done */
synchronized (loopMonitor) {
loopMonitor.notify();
}
} catch (Exception e) {
ReportBugTextGenerator.unexpectedException(e);
}
}
}

UserMessageGenerator

Full name: jfreerails.client.top.UserMessageGenerator

Documentation

/**
* This class inspects incoming moves and generates a user message if
* appropriate. It is also used to trigger sounds.
*
* @author Luke
*
*/

Source Code

/**
* This class inspects incoming moves and generates a user message if
* appropriate. It is also used to trigger sounds.
*
* @author Luke
*
*/
public class UserMessageGenerator implements MoveReceiver {
private ModelRoot modelRoot;
private ActionRoot actionRoot;
private final DecimalFormat formatter = new DecimalFormat("#,###,###");
private SoundManager soundManager = SoundManager.getSoundManager();
public UserMessageGenerator(ModelRoot mr, ActionRoot actionRoot) {
if (null == mr || null == actionRoot) {
throw new NullPointerException();
}
this.actionRoot = actionRoot;
this.modelRoot = mr;
}
public void processMove(Move move) {
if (move instanceof CompositeMove) {
ImList<Move> moves = ((CompositeMove) move).getMoves();
for (int i = 0; i < moves.size(); i++) {
processMove(moves.get(i));
}
}
if (move instanceof WorldDiffMove) {
WorldDiffMove wdm = (WorldDiffMove) move;
if (wdm.getCause().equals(WorldDiffMove.Cause.TrainArrives)) {
trainArrives(wdm);
}
} else if (move instanceof ChangeGameSpeedMove) {
logSpeed();
}
}
/** Generates a message giving details of any cargo delivered and plays
* a cash register sound to indicate that revenue is coming in.
*/
private void trainArrives(WorldDiffMove wdm) {
ArrayList<DeliverCargoReceipt> cargoDelivered = new ArrayList<DeliverCargoReceipt>();
CompositeMove listChanges = wdm.getListChanges();
for (int i = 0; i < listChanges.size(); i++) {
Move m = listChanges.getMoves().get(i);
if (m instanceof AddTransactionMove) {
AddTransactionMove atm = (AddTransactionMove) m;
if(!atm.getPrincipal().equals(modelRoot.getPrincipal())){
//We don't want to know about other players' income!
return;
}
Transaction t = atm.getTransaction();
if (t instanceof DeliverCargoReceipt) {
DeliverCargoReceipt receipt = (DeliverCargoReceipt) t;
cargoDelivered.add(receipt);
}
}
}
if (cargoDelivered.size() > 0) {
ReadOnlyWorld world = modelRoot.getWorld();
StringBuffer message = new StringBuffer();
DeliverCargoReceipt first = cargoDelivered.get(0);
int stationId = first.getStationId();
int trainId = first.getTrainId();
message.append("Train #");
message.append(trainId + 1); // So that the first train
// is #1, not #0.
message.append(" arrives at ");
StationModel station = (StationModel) world.get(modelRoot
.getPrincipal(), KEY.STATIONS, stationId);
message.append(station.getStationName());
message.append("\n");
long revenue = 0;
int[] cargoQuantities = new int[modelRoot.getWorld().size(
SKEY.CARGO_TYPES)];
for (DeliverCargoReceipt receipt : cargoDelivered) {
CargoBatch batch = receipt.getCb();
revenue += receipt.deltaCash().getAmount();
cargoQuantities[batch.getCargoType()] = receipt
.getQuantity();
}
for (int i = 0; i < cargoQuantities.length; i++) {
int j = cargoQuantities[i];
if (j > 0) {
CargoType cargoType = (CargoType) world.get(
SKEY.CARGO_TYPES, i);
message.append(j);
message.append(" ");
message.append(cargoType.getDisplayName());
message.append("\n");
}
}
message.append("Revenue $");
message.append(formatter.format(revenue));
modelRoot.setProperty(Property.QUICK_MESSAGE, message
.toString());
// Play the sound of cash coming in. The greater the
// revenue,
// the more loops of the sample we play.
int loops = (int) revenue / 4000;
try {
soundManager.playSound(
"/jfreerails/client/sounds/cash.wav", loops);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void logSpeed() {
ReadOnlyWorld world = modelRoot.getWorld();
GameSpeed speed = ((GameSpeed) world.get(ITEM.GAME_SPEED));
int gameSpeed = speed.getSpeed();
if (gameSpeed <= 0) {
modelRoot
.setProperty(Property.PERMANENT_MESSAGE, "Game is paused.");
/*
* Also hide any other message. It looks silly if it says "Game is
* paused." and "Game speed: fast" on screen at the same time!
*/
modelRoot.setProperty(Property.QUICK_MESSAGE, "");
} else {
modelRoot.setProperty(Property.PERMANENT_MESSAGE, null);
String gameSpeedDesc = actionRoot.getServerControls()
.getGameSpeedDesc(gameSpeed);
modelRoot.setProperty(Property.QUICK_MESSAGE, "Game speed: "
+ gameSpeedDesc);
}
}
}

StationTypesPopup

Full name: jfreerails.client.top.StationTypesPopup

Documentation

/**
* This JPopupMenu displays the list of station types that are available and
* builds the type that is selected.
*
* @author Luke Lindsay 08-Nov-2002
*
*/

Source Code

/**
* This JPopupMenu displays the list of station types that are available and
* builds the type that is selected.
*
* @author Luke Lindsay 08-Nov-2002
*
*/
public class StationTypesPopup extends JPopupMenu {
private static final long serialVersionUID = 3258415040658093364L;
private Point tileToBuildStationOn;
private StationRadiusRenderer stationRadiusRenderer;
private PopupMenuListener popupMenuListener;
private StationBuildModel stationBuildModel;
private ModelRoot modelRoot;
public StationTypesPopup() {
}
public boolean canBuiltStationHere(Point p) {
stationBuildModel.getStationBuildAction().putValue(
StationBuildModel.StationBuildAction.STATION_POSITION_KEY, p);
FreerailsTile tile = (FreerailsTile) modelRoot.getWorld().getTile(p.x,
p.y);
return tile.hasTrack();
}
private class StationBuildMenuItem extends JMenuItem {
private static final long serialVersionUID = 3256721792751120946L;
@Override
public void configurePropertiesFromAction(Action a) {
super.configurePropertiesFromAction(a);
}
}
public void setup(ModelRoot mr, ActionRoot actionRoot,
StationRadiusRenderer srr) {
modelRoot = mr;
stationBuildModel = actionRoot.getStationBuildModel();
stationRadiusRenderer = srr;
this.removeAll();
this.removePopupMenuListener(popupMenuListener);
popupMenuListener = new PopupMenuListener() {
public void popupMenuCanceled(PopupMenuEvent e) {
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
stationRadiusRenderer.hide();
stationBuildModel.getStationCancelAction().actionPerformed(
new ActionEvent(StationTypesPopup.this,
ActionEvent.ACTION_PERFORMED, ""));
}
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
stationRadiusRenderer.setPosition(tileToBuildStationOn.x,
tileToBuildStationOn.y);
stationBuildModel
.getStationBuildAction()
.putValue(
StationBuildModel.StationBuildAction.STATION_POSITION_KEY,
tileToBuildStationOn);
}
};
this.addPopupMenuListener(popupMenuListener);
final Action[] stationChooseActions = stationBuildModel
.getStationChooseActions();
for (int i = 0; i < stationChooseActions.length; i++) {
final StationBuildMenuItem rbMenuItem = new StationBuildMenuItem();
final int index = i;
rbMenuItem.configurePropertiesFromAction(stationChooseActions[i]);
rbMenuItem.setIcon(null);
// Show the relevant station radius when the station type's
// menu item gets focus.
rbMenuItem.addChangeListener(new ChangeListener() {
private boolean armed = false;
public void stateChanged(ChangeEvent e) {
if (rbMenuItem.isArmed() && (rbMenuItem.isArmed() != armed)) {
stationChooseActions[index]
.actionPerformed(new ActionEvent(rbMenuItem,
ActionEvent.ACTION_PERFORMED, ""));
}
armed = rbMenuItem.isArmed();
}
});
rbMenuItem.addActionListener(stationBuildModel
.getStationBuildAction());
add(rbMenuItem);
}
stationBuildModel.getStationBuildAction().addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if (e
.getPropertyName()
.equals(
StationBuildModel.StationBuildAction.STATION_RADIUS_KEY)) {
int newRadius = ((Integer) e.getNewValue())
.intValue();
stationRadiusRenderer.setRadius(newRadius);
}
if (stationBuildModel.getStationBuildAction()
.isEnabled()) {
stationRadiusRenderer.show();
} else {
stationRadiusRenderer.hide();
}
}
});
}
public void showMenu(Component invoker, int x, int y, Point tile) {
tileToBuildStationOn = tile;
super.show(invoker, x, y);
}
@Override
public void setVisible(boolean b) {
// If this popup is visible, we don't want the station's position to
// follow the mouse.
stationBuildModel.setPositionFollowsMouse(!b);
super.setVisible(b);
}
}

GUIComponentFactoryImpl

Full name: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

/**
* Creates and wires up the GUI components.
*
* @author Luke
*/

Source Code

/**
* Creates and wires up the GUI components.
*
* @author Luke
*/
public class GUIComponentFactoryImpl implements GUIComponentFactory,
WorldMapListener, WorldListListener {
/** Whether to show certain 'cheat' menus used for testing. */
private static final boolean CHEAT = (System.getProperty("cheat") != null);
private static final Logger logger = Logger
.getLogger(GUIComponentFactoryImpl.class.getName());
private final ActionRoot actionRoot;
private final BuildMenu buildMenu;
private final CashJLabel cashjLabel;
private final ClientJFrame clientJFrame;
private final DateJLabel datejLabel;
private final DialogueBoxController dialogueBoxController;
private JMenu displayMenu;
private JMenu helpMenu;
private JMenu brokerMenu;
private boolean isSetup = false;
private JMenuItem leaderBoardJMenuItem;
private DetailMapRenderer mainMap;
private final JScrollPane mainMapScrollPane1;
private final MapViewJComponentConcrete mapViewJComponent;
private final ModelRootImpl modelRoot;
private JMenuItem networthGraphJMenuItem;
private MapRenderer overviewMap;
private final JPanel overviewMapContainer;
private final Rectangle r = new Rectangle(10, 10, 10, 10);
private JMenu reportsMenu;
private ServerControlModel sc;
private ActionAdapter speedActions;
private JMenuItem stationInfoJMenuItem;
private final StationTypesPopup stationTypesPopup;
private JMenuItem trainListJMenuItem;
private JMenuItem trainOrdersJMenuItem;
private JMenuItem callBrokerJMenuItem;
/**
* This is the panel at the bottom right of the screen.
*/
private final RHSJTabPane trainsJTabPane;
private final UserInputOnMapController userInputOnMapController;
private UserMessageGenerator userMessageGenerator;
private RenderersRoot renderers;
private ReadOnlyWorld world;
public GUIComponentFactoryImpl(ModelRootImpl mr, ActionRoot ar) {
modelRoot = mr;
actionRoot = ar;
userInputOnMapController = new UserInputOnMapController(modelRoot, ar);
buildMenu = new jfreerails.client.top.BuildMenu();
mapViewJComponent = new MapViewJComponentConcrete();
mainMapScrollPane1 = new JScrollPane();
overviewMapContainer = new OverviewMapJComponent(r);
stationTypesPopup = new StationTypesPopup();
MainMapAndOverviewMapMediator mediator = new MainMapAndOverviewMapMediator();
mediator.setup(overviewMapContainer, mainMapScrollPane1.getViewport(),
mapViewJComponent, r);
trainsJTabPane = new RHSJTabPane();
datejLabel = new DateJLabel();
cashjLabel = new CashJLabel();
clientJFrame = new ClientJFrame(this);
dialogueBoxController = new DialogueBoxController(clientJFrame,
modelRoot);
actionRoot.setDialogueBoxController(dialogueBoxController);
modelRoot.addSplitMoveReceiver(new MoveReceiver() {
public void processMove(Move move) {
if (move instanceof ChangeGameSpeedMove) {
ChangeGameSpeedMove speedMove = (ChangeGameSpeedMove) move;
for (Enumeration<Action> actionsEnum = speedActions
.getActions(); actionsEnum.hasMoreElements();) {
Action action = actionsEnum.nextElement();
String actionName = (String) action
.getValue(Action.NAME);
if (actionName.equals(actionRoot.getServerControls()
.getGameSpeedDesc(speedMove.getNewSpeed()))) {
speedActions.setSelectedItem(actionName);
}
break;
}
}
}
});
userMessageGenerator = new UserMessageGenerator(this.modelRoot,
this.actionRoot);
modelRoot.addCompleteMoveReceiver(userMessageGenerator);
}
private void countStations() {
NonNullElements stations = new NonNullElements(KEY.STATIONS, modelRoot
.getWorld(), modelRoot.getPrincipal());
boolean enabled;
if (stations.size() > 0) {
enabled = true;
} else {
enabled = false;
}
this.trainsJTabPane.setStationTabEnabled(enabled);
this.stationInfoJMenuItem.setEnabled(enabled);
}
private void countTrains() {
NonNullElements trains = new NonNullElements(KEY.TRAINS, modelRoot
.getWorld(), modelRoot.getPrincipal());
boolean enabled;
if (trains.size() > 0) {
enabled = true;
} else {
enabled = false;
}
this.trainsJTabPane.setTrainTabEnabled(enabled);
this.trainListJMenuItem.setEnabled(enabled);
this.trainOrdersJMenuItem.setEnabled(enabled);
}
public JMenu createBuildMenu() {
return buildMenu;
}
public JLabel createCashJLabel() {
return cashjLabel;
}
public JFrame createClientJFrame(String title) {
clientJFrame.setTitle(title);
return clientJFrame;
}
public JLabel createDateJLabel() {
return datejLabel;
}
public JMenu createBrokerMenu() {
brokerMenu = new JMenu("Broker");
callBrokerJMenuItem = new JMenuItem("Call Broker");
callBrokerJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showBrokerScreen();
}
});
brokerMenu.add(callBrokerJMenuItem);
return brokerMenu;
}
public JMenu createDisplayMenu() {
displayMenu = new JMenu("Display");
displayMenu.setMnemonic(68);
trainOrdersJMenuItem = new JMenuItem("Train Orders");
trainOrdersJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showTrainOrders();
}
});
stationInfoJMenuItem = new JMenuItem("Station Info");
stationInfoJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showStationInfo(0);
}
});
trainListJMenuItem = new JMenuItem("Train List");
trainListJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showTrainList();
}
});
displayMenu.add(trainOrdersJMenuItem);
displayMenu.add(stationInfoJMenuItem);
displayMenu.add(trainListJMenuItem);
displayMenu.addSeparator();
// Add menu items to control what gets displayed on the map.
final JCheckBoxMenuItem showCargoMenuItem = new JCheckBoxMenuItem(
"Show cargo at stations", true);
displayMenu.add(showCargoMenuItem);
showCargoMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modelRoot.setProperty(
ModelRoot.Property.SHOW_CARGO_AT_STATIONS, new Boolean(
showCargoMenuItem.isSelected()));
mapViewJComponent.refreshAll();
}
});
final JCheckBoxMenuItem showStationNamesMenuItem = new JCheckBoxMenuItem(
"Show station names", true);
displayMenu.add(showStationNamesMenuItem);
showStationNamesMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modelRoot.setProperty(ModelRoot.Property.SHOW_STATION_NAMES,
new Boolean(showStationNamesMenuItem.isSelected()));
mapViewJComponent.refreshAll();
}
});
final JCheckBoxMenuItem showStationBordersMenuItem = new JCheckBoxMenuItem(
"Show sphere-of-influence around stations", true);
displayMenu.add(showStationBordersMenuItem);
showStationBordersMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modelRoot.setProperty(ModelRoot.Property.SHOW_STATION_BORDERS,
new Boolean(showStationBordersMenuItem.isSelected()));
mapViewJComponent.refreshAll();
}
});
final JCheckBoxMenuItem playSoundsMenuItem = new JCheckBoxMenuItem(
"Play sounds", true);
displayMenu.add(playSoundsMenuItem);
playSoundsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modelRoot.setProperty(ModelRoot.Property.PLAY_SOUNDS,
new Boolean(playSoundsMenuItem.isSelected()));
}
});
;
boolean showFps = Boolean.parseBoolean(System.getProperty("SHOWFPS"));
final JCheckBoxMenuItem showFPSMenuItem = new JCheckBoxMenuItem(
"Show FPS stats", showFps);
displayMenu.add(showFPSMenuItem);
showFPSMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String newValue = String.valueOf(showFPSMenuItem.isSelected());
System.setProperty("SHOWFPS", newValue);
}
});
return displayMenu;
}
public JMenu createGameMenu() {
sc = actionRoot.getServerControls();
JMenu gameMenu = new JMenu("Game");
gameMenu.setMnemonic(71);
JMenuItem quitJMenuItem = new JMenuItem("Exit Game");
quitJMenuItem.setMnemonic(88);
quitJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
final JMenu newGameJMenu = new JMenu(sc.getNewGameAction());
newGameJMenu.addMenuListener(new MenuListener() {
public void menuCanceled(MenuEvent e) {
}
public void menuDeselected(MenuEvent e) {
}
public void menuSelected(MenuEvent e) {
newGameJMenu.removeAll();
Enumeration<Action> actions = sc.getMapNames().getActions();
while (actions.hasMoreElements()) {
JMenuItem mi = new JMenuItem(actions.nextElement());
newGameJMenu.add(mi);
}
}
});
JMenuItem saveGameJMenuItem = new JMenuItem(sc.getSaveGameAction());
JMenuItem loadGameJMenuItem = new JMenuItem(sc.getLoadGameAction());
// Fix bug 1102806 Newspaper does nothing, so hide it.
// JMenuItem newspaperJMenuItem = new JMenuItem("Newspaper");
// newspaperJMenuItem.setMnemonic(78);
// newspaperJMenuItem.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// dialogueBoxController.showNewspaper("Headline");
// //glassPanel.setVisible(true);
// }
// });
// Set up the game speed sub-menu.
JMenu gameSpeedSubMenu = new JMenu("Game Speed");
ButtonGroup group = new ButtonGroup();
speedActions = sc.getSetTargetTickPerSecondActions();
Enumeration<MappedButtonModel> buttonModels = speedActions
.getButtonModels();
Enumeration<Action> actions = speedActions.getActions();
while (buttonModels.hasMoreElements()) {
JRadioButtonMenuItem mi = new JRadioButtonMenuItem(actions
.nextElement());
mi.setModel(buttonModels.nextElement());
group.add(mi);
gameSpeedSubMenu.add(mi);
}
gameMenu.add(newGameJMenu);
gameMenu.addSeparator();
gameMenu.add(loadGameJMenuItem);
gameMenu.add(saveGameJMenuItem);
gameMenu.addSeparator();
gameMenu.add(gameSpeedSubMenu);
// gameMenu.add(newspaperJMenuItem);
gameMenu.addSeparator();
gameMenu.add(quitJMenuItem);
if (CHEAT) {
/** For testing. */
final ActionListener build200trains = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
WorldIterator wi = new NonNullElements(KEY.STATIONS,
modelRoot.getWorld(), modelRoot.getPrincipal());
if (wi.next()) {
Random randy = new Random();
StationModel station = (StationModel) wi.getElement();
ImList<PlannedTrain> before = station
.getProduction();
int numberOfEngineTypes = modelRoot.getWorld().size(
SKEY.ENGINE_TYPES) - 1;
int numberOfcargoTypes = modelRoot.getWorld().size(
SKEY.CARGO_TYPES) - 1;
PlannedTrain[] temp = new PlannedTrain[200];
for (int i = 0; i < temp.length; i++) {
int engineType = randy.nextInt(numberOfEngineTypes);
int[] wagonTypes = new int[] {
randy.nextInt(numberOfcargoTypes),
randy.nextInt(numberOfcargoTypes),
randy.nextInt(numberOfcargoTypes) };
PlannedTrain plannedTrain = new PlannedTrain(engineType, wagonTypes);
temp[i] = plannedTrain;
}
ImList<PlannedTrain> after = new ImList<PlannedTrain>(temp);
Move m = new ChangeProductionAtEngineShopMove(before,
after, wi.getIndex(), modelRoot.getPrincipal());
modelRoot.doMove(m);
}
}
};
JMenuItem build200TrainsMenuItem = new JMenuItem(
"Build 200 trains!");
build200TrainsMenuItem.addActionListener(build200trains);
gameMenu.add(build200TrainsMenuItem);
}
return gameMenu;
}
public JMenu createHelpMenu() {
helpMenu = new javax.swing.JMenu("Help");
JMenuItem about = new JMenuItem("About");
about.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showAbout();
}
});
JMenuItem how2play = new JMenuItem("Getting started");
how2play.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showHow2Play();
}
});
JMenuItem showControls = new JMenuItem("Show game controls");
showControls.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showGameControls();
}
});
JMenuItem showJavaProperties = new JMenuItem("Show Java Properties");
showJavaProperties
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showJavaProperties();
}
});
JMenuItem showReportBug = new JMenuItem("Report Bug");
showReportBug.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showReportBug();
}
});
helpMenu.add(showControls);
helpMenu.add(how2play);
helpMenu.add(showJavaProperties);
helpMenu.add(showReportBug);
helpMenu.add(about);
return helpMenu;
}
public JScrollPane createMainMap() {
return mainMapScrollPane1;
}
public JPanel createOverviewMap() {
return overviewMapContainer;
}
public JMenu createReportsMenu() {
reportsMenu = new javax.swing.JMenu("Reports");
JMenuItem incomeStatementJMenuItem = new JMenuItem("Income Statement");
incomeStatementJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showIncomeStatement();
}
});
JMenuItem balanceSheetJMenuItem = new JMenuItem("Balance Sheet");
balanceSheetJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showBalanceSheet();
}
});
leaderBoardJMenuItem = new JMenuItem("Leaderboard");
leaderBoardJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showLeaderBoard();
}
});
networthGraphJMenuItem = new JMenuItem("Networth Graph");
networthGraphJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showNetworthGraph();
}
});
reportsMenu.add(balanceSheetJMenuItem);
reportsMenu.add(incomeStatementJMenuItem);
reportsMenu.add(leaderBoardJMenuItem);
reportsMenu.add(networthGraphJMenuItem);
return reportsMenu;
}
public JTabbedPane createTrainsJTabPane() {
return trainsJTabPane;
}
public BuildTrackController getBuildTrackController() {
return mainMap.getBuildTrackController();
}
public boolean isSetup() {
return isSetup;
}
public void itemAdded(KEY key, int index, FreerailsPrincipal principal) {
boolean rightPrincipal = principal
.equals(this.modelRoot.getPrincipal());
if (KEY.TRAINS == key && rightPrincipal) {
countTrains();
} else if (KEY.STATIONS == key && rightPrincipal) {
countStations();
}
}
public void itemRemoved(KEY key, int index, FreerailsPrincipal principal) {
// do nothing
}
public void listUpdated(KEY key, int index, FreerailsPrincipal principal) {
boolean rightPrincipal = principal
.equals(this.modelRoot.getPrincipal());
if (KEY.TRAINS == key && rightPrincipal) {
countTrains();
} else if (KEY.STATIONS == key && rightPrincipal) {
countStations();
}
}
/**
* Called when a new game is started or a game is loaded.
* <p>
* <b>Be extremely careful with the references of objects allocated in this
* method to avoid memory leaks - see bug 967677 (OutOfMemoryError after
* starting several new games). </b>
* </p>
*/
public void setup(RenderersRoot vl, ReadOnlyWorld w) throws IOException {
/*
* Set the cursor position. The initial cursor position is 0,0. However,
* if a game is loaded or a new game is started and the map size is the
* same as the last map size, then the cursor should take the position
* it had on the last map.
*/
ImPoint cursorPosition = new ImPoint(0, 0);
if (null != world) {
if (w.getMapWidth() == world.getMapWidth()
&& w.getMapHeight() == world.getMapHeight()) {
cursorPosition = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.CURSOR_POSITION);
}
}
renderers = vl;
world = w;
modelRoot.addMapListener(this);
modelRoot.addListListener(this);
if (!vl.validate(world)) {
throw new IllegalArgumentException("The specified"
+ " RenderersRoot are not compatible with the clients"
+ "world!");
}
// create the main and overview maps
mainMap = new DetailMapRenderer(world, renderers, modelRoot);
TrainRenderer trainRenderer = mainMap.getTrainRenderer();
Dimension maxSize = new Dimension(200, 200);
overviewMap = ZoomedOutMapRenderer.getInstance(world, maxSize);
stationTypesPopup.setup(modelRoot, actionRoot, mainMap
.getStationRadius());
mapViewJComponent
.setup(mainMap, modelRoot, renderers);
// setup the the main and overview map JComponents
dialogueBoxController.setDefaultFocusOwner(mapViewJComponent);
userInputOnMapController.setup(mapViewJComponent, actionRoot
.getTrackMoveProducer(), stationTypesPopup, this.modelRoot,
dialogueBoxController, mapViewJComponent.getMapCursor(),
getBuildTrackController(), trainRenderer);
buildMenu.setup(actionRoot);
mainMapScrollPane1.setViewportView(this.mapViewJComponent);
((OverviewMapJComponent) overviewMapContainer).setup(overviewMap);
datejLabel.setup(modelRoot, vl, null);
cashjLabel.setup(modelRoot, vl, null);
trainsJTabPane.setup(actionRoot, vl, modelRoot);
dialogueBoxController.setup(modelRoot, vl);
StationPlacementCursor.wireUp(actionRoot, mainMap.getStationRadius(),
mapViewJComponent);
int gameSpeed = ((GameSpeed) world.get(ITEM.GAME_SPEED)).getSpeed();
/* Set the selected game speed radio button. */
String actionName = actionRoot.getServerControls().getGameSpeedDesc(
gameSpeed);
speedActions.setSelectedItem(actionName);
userMessageGenerator.logSpeed();
/*
* Count stations and trains to determine if we need to display the
* station and train menu items and tabs.3
*/
countStations();
countTrains();
String name = modelRoot.getPrincipal().getName();
String serverDetails = (String) modelRoot
.getProperty(ModelRoot.Property.SERVER);
String frameTitle;
if (serverDetails.equals(LocalConnection.SERVER_IN_SAME_JVM)) {
frameTitle = name + " - Freerails";
} else {
frameTitle = name + " - " + serverDetails + " - Freerails";
}
clientJFrame.setTitle(frameTitle);
isSetup = true;
modelRoot.setProperty(ModelRoot.Property.CURSOR_POSITION,
cursorPosition);
mapViewJComponent.requestFocus();
}
/**
* Listens for changes on the map, for instance when track is built, and
* refreshes the map views.
*/
public void tilesChanged(Rectangle tilesChanged) {
logger.fine("TilesChanged = " + tilesChanged);
// If lots of tiles have changed, do a complete refresh.
int size = tilesChanged.width * tilesChanged.height;
if (size > 100) {
mainMap.refreshAll();
overviewMap.refreshAll();
} else {
Point tile = new Point();
// Fix for bug 967673 (Crash when building track close to edge of
// map).
Rectangle mapRect = new Rectangle(0, 0, world.getMapWidth(), world
.getMapHeight());
tilesChanged = tilesChanged.intersection(mapRect);
for (tile.x = tilesChanged.x; tile.x < (tilesChanged.x + tilesChanged.width); tile.x++) {
for (tile.y = tilesChanged.y; tile.y < (tilesChanged.y + tilesChanged.height); tile.y++) {
mainMap.refreshTile(tile.x, tile.y);
overviewMap.refreshTile(tile.x, tile.y);
}
}
}
}
}

FPScounter

Full name: jfreerails.client.top.FPScounter

Documentation

/**
* Provides a method that draws a String showing the average FPS over the last
* complete 5000ms interval.
*
* @author Luke
*
*/

Source Code

/**
* Provides a method that draws a String showing the average FPS over the last
* complete 5000ms interval.
*
* @author Luke
*
*/
public class FPScounter {
private final double[] fpsValues = new double[400];
private int newFrameCount = 0;
private String newFPSstr = "starting..";
private long lastFrameTime;
private final int fontSize;
private final Color bgColor;
FPScounter() {
this.fontSize = 10;
bgColor = new Color(0, 0, 128);
}
// Display the average number of FPS.
void updateFPSCounter() {
long currentTime = System.nanoTime();
if (newFrameCount == 0) {
lastFrameTime = currentTime;
}
double dt = currentTime - lastFrameTime;
double fps = 1000000000d / dt;
fpsValues[newFrameCount % fpsValues.length] = fps;
newFrameCount++;
int n = fpsValues.length;
if (newFrameCount > fpsValues.length) {
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
double mean = 0;
for (int i = 0; i < fpsValues.length; i++) {
min = Math.min(min, fpsValues[i]);
max = Math.max(max, fpsValues[i]);
mean += fpsValues[i];
}
mean = mean / n;
if (mean > max)
throw new IllegalStateException();
if (mean < min)
throw new IllegalStateException();
double variance = 0;
for (int i = 0; i < fpsValues.length; i++) {
double xMinusU = fpsValues[i] - mean;
variance += xMinusU * xMinusU;
}
variance = variance / n;
if (newFrameCount % 20 == 0) {
StringBuffer sb = new StringBuffer();
sb.append("FPS\n");
sb.append(" n ");
sb.append(n);
sb.append('\n');
sb.append(" \u03BC ");
sb.append(Math.round(mean));
sb.append('\n');
sb.append(" \u03C3 ");
sb.append(Math.round(Math.sqrt(variance)));
sb.append('\n');
sb.append(" min ");
sb.append(Math.round(min));
sb.append('\n');
sb.append(" max ");
sb.append(Math.round(max));
sb.append('\n');
newFPSstr = sb.toString();
}
}
// g.setColor(Color.WHITE);
// g.fillRect(50, 50, 50, 20);
// g.setColor(Color.BLACK);
// g.drawString(newFPSstr, 50, 65);
lastFrameTime = currentTime;
}
void drawFPS(Graphics2D g) {
int rectWidth;
int rectHeight;
int rectX;
int rectY;
int positionX = 50;
int positionY = 70;
Color textColor = Color.WHITE;
String[] lines = newFPSstr.split("\n");
rectWidth = 60;
rectHeight = (int) ((fontSize + 1) * 1.2 * lines.length);
rectY = (int) (positionY - fontSize * 1.2);
rectX = positionX;
g.setColor(bgColor);
g.fillRect(rectX, rectY, rectWidth, rectHeight);
g.setColor(textColor);
// g.setFont(font);
for (String s : lines) {
g.drawString(s, positionX, positionY);
positionY += fontSize * 1.2;
}
}
}

add

Class: jfreerails.util.IntArray

Documentation

/**
* Add a value to the array, appending it after the current values.
*
* @param value
* value to be added
* @return index number of added element
*/

Source Code

/**
* Add a value to the array, appending it after the current values.
*
* @param value
* value to be added
* @return index number of added element
*/
public final int add(int value) {
int index = getAddIndex();
baseArray[index] = value;
return index;
}

Bill

Class: jfreerails.world.accounts.Bill

Documentation

/**
* Constructs a new Bill with the specified amount and category.
* The amount is stored as a negative value to represent debt.
*
* @param amount the monetary amount of the bill, which will be stored as negative
* @param category the category used to classify this bill
*/

Source Code

public Bill(Money amount, Category category) {
this.amount = new Money(-amount.getAmount());
this.category = category;
}

parse

Class: jfreerails.server.parser.Track_TilesParser

Documentation

/**
* The recognizer entry method taking a URL.
*
* @param url
* URL source to be parsed.
* @throws java.io.IOException
* on I/O error.
* @throws SAXException
* propagated exception thrown by a DocumentHandler.
* @throws javax.xml.parsers.ParserConfigurationException
* a parser satisfying requested configuration can not be
* created.
*/

Source Code

/**
* The recognizer entry method taking a URL.
*
* @param url
* URL source to be parsed.
* @throws java.io.IOException
* on I/O error.
* @throws SAXException
* propagated exception thrown by a DocumentHandler.
* @throws javax.xml.parsers.ParserConfigurationException
* a parser satisfying requested configuration can not be
* created.
*/
public static void parse(final java.net.URL url,
final Track_TilesHandler handler) throws SAXException,
ParserConfigurationException, IOException {
parse(new InputSource(url.toExternalForm()), handler);
}

next

Class: jfreerails.world.top.WorldIterator

Documentation

/**
* Moves the cursor down one row from its current position.
*/

Source Code

/**
* Moves the cursor down one row from its current position.
*/
boolean next();

Called Methods

No outgoing method calls

nextActivity

Class: jfreerails.world.top.ActivityIteratorImpl

Documentation

/**
* Advances the iterator to the next activity in the sequence.
* This method first checks if there is a next activity using {@link #hasNext()}.
* If no next activity exists, a {@link NoSuchElementException} is thrown.
* Otherwise, the internal activity index is incremented, and the next activity
* is retrieved from the current list.
*
* @throws NoSuchElementException if there are no more activities to retrieve.
*/

Source Code

public void nextActivity() {
if (!hasNext()) {
throw new NoSuchElementException();
}
activityIndex++;
ant = currentList.get(activityIndex);
}

Called Methods

  • jfreerails.world.top.WorldImpl.ActivityIteratorImpl.hasNext (external)

equals

Class: jfreerails.network.specifics.LogOnRequest

Documentation

/**
* Overrides the equals method to compare LogOnRequest objects based on their username and password fields.
* Two LogOnRequest instances are considered equal if they have the same username and password values,
* with proper handling of null values.
*
* @param o the object to compare with this LogOnRequest instance
* @return true if the objects are equal, false otherwise
*/

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof LogOnRequest))
return false;
final LogOnRequest logOnRequest = (LogOnRequest) o;
if (password != null ? !password.equals(logOnRequest.password)
: logOnRequest.password != null)
return false;
if (username != null ? !username.equals(logOnRequest.username)
: logOnRequest.username != null)
return false;
return true;
}

Called Methods

No outgoing method calls

duration

Class: jfreerails.world.top.TestActivity

Documentation

/**
* Returns the duration value stored in this object.
*
* @return the duration in seconds
*/

Source Code

public double duration() {
return duration;
}

Called Methods

No outgoing method calls

exitForm

Class: jfreerails.launcher.Launcher

Documentation

/** Exit the Application. */

Source Code

/** Exit the Application. */
private void exitForm(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_exitForm
System.exit(0);
}// GEN-LAST:event_exitForm

Called Methods

No outgoing method calls

ServerGameModelImpl

Class: jfreerails.server.ServerGameModelImpl

Documentation

/**
* Initializes a new instance of the ServerGameModelImpl class with the specified game world
* and collection of server automata. This constructor sets up the internal state by assigning
* the provided world and automata, and records the time when the next model update is due.
*
* @param w the game world representing the current state of the simulation
* @param serverAutomata a vector of server automata responsible for managing game logic
* @throws IllegalArgumentException if the provided parameters are null or invalid
*/

Source Code

public ServerGameModelImpl( World w,
Vector<ServerAutomaton> serverAutomata) {
this.world = w;
this.serverAutomata = serverAutomata;
nextModelUpdateDue = System.currentTimeMillis();
}

Called Methods

No outgoing method calls

controlPoint

Class: experimental.TrackRenderer

Documentation

/**
* Calculates a control point based on the given source point.
* The new point is computed by applying a weight of 0.3 to the source coordinates
* and adjusting them relative to the tile width. This transformation is used
* to position control points for rendering purposes.
*
* @param from The source point used to compute the control point.
* @return A new Point2D.Double representing the transformed control point.
*/

Source Code

private Point2D.Double controlPoint(Point2D.Double from) {
double weight = 0.3;
double x = from.getX() * weight + tileWidth * (1 - weight);
double y = from.getY() * weight + tileWidth * (1 - weight);
return new Point2D.Double(x, y);
}

Called Methods

No outgoing method calls

getScale

Class: jfreerails.client.renderer.ZoomedOutMapRenderer

Documentation

/**
* Returns the scale factor as a float, calculated by dividing the image height
* by the map height. This scale factor represents the zoom level applied to
* the map rendering.
*
* @return the scale factor as a float value
*/

Source Code

public float getScale() {
return (float) imageHeight / (float) mapHeight;
}

Called Methods

No outgoing method calls

formKeyTyped

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

/**
* Handles the key typed event by invoking the doClick method on the viewMode.
* This method is triggered when a key is typed in the associated component,
* causing the view mode to perform its default click action.
*
* @param evt the KeyEvent object representing the key typed event
*/

Source Code

private void formKeyTyped(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_formKeyTyped
viewMode.doClick();
}// GEN-LAST:event_formKeyTyped

Called Methods

No outgoing method calls

TrainPathFinder

Class: jfreerails.server.TrainPathFinder

Documentation

/**
* Constructs a new TrainPathFinder with the specified parameters.
*
* @param tx the FlatTrackExplorer used to navigate the track layout
* @param w the ReadOnlyWorld representing the current game world state
* @param trainNumber the unique identifier for the train
* @param newMr the MoveReceiver responsible for handling move events
* @param p the FreerailsPrincipal representing the user's permissions or identity
*
* @throws IllegalArgumentException if any parameter is null or invalid
*/

Source Code

public TrainPathFinder(FlatTrackExplorer tx, ReadOnlyWorld w,
int trainNumber, MoveReceiver newMr, FreerailsPrincipal p) {
this.trackExplorer = tx;
this.trainId = trainNumber;
principal = p;
stopsHandler = new TrainStopsHandler(trainId, principal, new WorldDiffs(w));
this.mr = newMr;
this.w = w;
}

Called Methods

No outgoing method calls

addTrackActionPerformed

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

/**
* Handles the action event triggered when the "Add Track" button is clicked.
* This method updates the UI visibility settings, cancels any ongoing station placement,
* and switches the track builder mode to {@code BUILD_TRACK}.
*
* @param evt The {@code ActionEvent} triggered by the user's interaction with the "Add Track" button.
*/

Source Code

private void addTrackActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addTrackActionPerformed
setVisible(true, true, true, false);
cancelStationPlacement();
setTrackBuilderMode(BUILD_TRACK);
}// GEN-LAST:event_addTrackActionPerformed

initComponents

Class: jfreerails.client.view.CargoWaitingAndDemandedJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
stationName = new javax.swing.JLabel();
waiting = new javax.swing.JLabel();
waitingJTable = new javax.swing.JTable();
demands = new javax.swing.JLabel();
demandsJList = new javax.swing.JList();
spacer = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(100, 200));
jScrollPane1.setBorder(null);
jScrollPane1
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
jPanel1.setLayout(new java.awt.GridBagLayout());
stationName.setText("Station Name");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(6, 6, 6, 6);
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
jPanel1.add(stationName, gridBagConstraints);
waiting.setText("Waiting");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
jPanel1.add(waiting, gridBagConstraints);
waitingJTable.setBackground(javax.swing.UIManager.getDefaults()
.getColor("Button.background"));
waitingJTable.setFont(new java.awt.Font("Dialog", 0, 10));
waitingJTable.setModel(new javax.swing.table.DefaultTableModel(
new Object[][] { { "Mail", "4" }, { "Passengers", null } },
new String[] { "Title 1", "Title 2" }));
waitingJTable
.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
waitingJTable.setFocusable(false);
waitingJTable.setRequestFocusEnabled(false);
waitingJTable.setRowSelectionAllowed(false);
waitingJTable.setShowHorizontalLines(false);
waitingJTable.setShowVerticalLines(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
jPanel1.add(waitingJTable, gridBagConstraints);
demands.setText("Demands");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel1.add(demands, gridBagConstraints);
demandsJList.setBackground(javax.swing.UIManager.getDefaults()
.getColor("Button.background"));
demandsJList.setFont(new java.awt.Font("Dialog", 0, 10));
demandsJList.setFocusable(false);
demandsJList.setRequestFocusEnabled(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
jPanel1.add(demandsJList, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel1.add(spacer, gridBagConstraints);
jScrollPane1.setViewportView(jPanel1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}// GEN-END:initComponents

Called Methods

No outgoing method calls

getStroke4Curve

Class: experimental.TrackRenderer

Documentation

/**
* Generates the Stroke used to draw the sleepers for track section
* represented by the specified curve.
*/

Source Code

/**
* Generates the Stroke used to draw the sleepers for track section
* represented by the specified curve.
*/
public BasicStroke getStroke4Curve(CubicCurve2D.Double curve) {
PathIterator fpt = curve.getPathIterator(new AffineTransform(), 0.01);
double length = 0;
double[] coords = new double[6];
double x, y;
fpt.currentSegment(coords);
double lastX = coords[0];
double lastY = coords[1];
for (; !fpt.isDone(); fpt.next()) {
fpt.currentSegment(coords);
x = coords[0];
y = coords[1];
double dx = x - lastX;
double dy = y - lastY;
length += Math.sqrt(dx * dx + dy * dy);
lastX = x;
lastY = y;
}
float sleepers = (float) length / (targetSleeperGap + sleeperWidth);
float sleeperCount = (int) sleepers;
float sleeperGap = (float) length / sleeperCount - sleeperWidth;
float dash1[] = { sleeperWidth, sleeperGap };
float phase = sleeperWidth + (sleeperGap / 2);
return new BasicStroke((float) sleeperLength, BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER, 10.0f, dash1, phase);
}

Called Methods

No outgoing method calls

deltaCash

Class: jfreerails.world.accounts.Bill

Documentation

/**
* Returns the amount of money represented by this bill as a Money object.
* This value represents the delta (change) in cash associated with the bill.
*
* @return the amount of money as a Money object
*/

Source Code

public Money deltaCash() {
return amount;
}

Called Methods

No outgoing method calls

ChangeStationMove

Class: jfreerails.move.ChangeStationMove

Documentation

/**
* Constructs a new ChangeStationMove instance that represents changing a station
* at the specified index in a list. The move replaces the station at the given
* index with the new station, using the provided principal for authorization.
*
* @param index the index of the station to be changed in the list
* @param before the StationModel representing the station before the change
* @param after the StationModel representing the new station after the change
* @param p the FreerailsPrincipal used to validate the operation's permissions
*/

Source Code

public ChangeStationMove(int index, StationModel before,
StationModel after, FreerailsPrincipal p) {
super(KEY.STATIONS, index, before, after, p);
}

trainPos2Tiles

Class: jfreerails.server.TrainUpdater

Documentation

/**
* Converts a train's position on the map into an array of tile coordinates.
* Each tile coordinate is calculated by dividing the train's X and Y positions
* by the TILE_WIDTH (30) to map the continuous position to a grid of tiles.
*
* @param pos The train's position on the map, which contains methods to retrieve
*            the X, Y coordinates, and the length (number of tiles the train occupies)
* @return An array of ImPoint objects representing the tile coordinates for each
*         segment of the train's position
*/

Source Code

public static ImPoint[] trainPos2Tiles(TrainPositionOnMap pos) {
ImPoint[] returnValue = new ImPoint[pos.getLength()];
final int TILE_WIDTH = 30;
for (int i = 0; i < returnValue.length; i++) {
returnValue[i] = new ImPoint(pos.getX(i) / TILE_WIDTH, pos.getY(i)
/ TILE_WIDTH);
}
return returnValue;
}

WorldDiffMove

Class: jfreerails.move.WorldDiffMove

Documentation

/**
* Constructs a {@code WorldDiffMove} by processing differences between the current world state
* and the provided {@code WorldDiffs}, generating a sequence of moves representing the changes.
*
* @param world the current world state used to retrieve old values before changes
* @param worldDiffs the {@code WorldDiffs} object containing the differences to apply
* @param cause the cause of this move, used for tracking or logging purposes
*
* @throws UnsupportedOperationException if a change requires reducing the size of a list or transaction collection,
*         which is not supported in this context
*/

Source Code

public WorldDiffMove(ReadOnlyWorld world, WorldDiffs worldDiffs, Cause cause) throws UnsupportedOperationException {
this.cause = cause;
Iterator<ImPoint> mit = worldDiffs.getMapDiffs();
ArrayList<MapDiff> diffsArrayList = new ArrayList<MapDiff>();
while (mit.hasNext()) {
ImPoint p = mit.next();
FreerailsSerializable oldTile = world.getTile(p.x, p.y);
FreerailsSerializable newTile = worldDiffs.getTile(p.x, p.y);
diffsArrayList.add(new MapDiff(oldTile, newTile, p));
}
diffs = new ImList<MapDiff>(diffsArrayList);
x = 0;
y = 0;
w = world.getMapWidth();
h = world.getMapHeight();
List<Move> tempList = new ArrayList<Move>();
Iterator<ListKey> lit = worldDiffs.getListDiffs();
while (lit.hasNext()) {
ListKey lkey = lit.next();
WorldDiffs.LISTID listId = (LISTID) lkey.getListID();
switch (listId) {
case LISTS: {
int playerId = lkey.getIndex()[0];
FreerailsPrincipal fp = worldDiffs.getPlayer(playerId)
.getPrincipal();
KEY k = KEY.getKey(lkey.getIndex()[1]);
if (lkey.getType() == Element) {
Move m;
int elementId = lkey.getIndex()[2];
// Are we changing an element?
if (elementId < world.size(fp, k)) {
FreerailsSerializable before = world.get(fp, k,
elementId);
FreerailsSerializable after = worldDiffs.get(fp, k,
elementId);
m = new ChangeItemInListMove(k, elementId, before,
after, fp);
} else {
FreerailsSerializable element = worldDiffs.get(fp, k,
elementId);
m = new AddItemToListMove(k, elementId, element, fp);
}
tempList.add(m);
} else {
assert (lkey.getType() == EndPoint);
Integer newSize = (Integer) worldDiffs.getDiff(lkey);
int oldSize = world.size(fp, k);
if (newSize < oldSize) {
throw new UnsupportedOperationException();
}
}
break;
}
case CURRENT_BALANCE:
// Do nothing. The transaction moves should take care of changing
// the values of current balance.
break;
case BANK_ACCOUNTS: {
int playerId = lkey.getIndex()[0];
FreerailsPrincipal fp = worldDiffs.getPlayer(playerId)
.getPrincipal();
if (lkey.getType() == Element) {
Move m;
int elementId = lkey.getIndex()[1];
// Are we changing an element?
if (elementId < world.getNumberOfTransactions(fp)) {
throw new UnsupportedOperationException();
}
Transaction t = worldDiffs.getTransaction(fp, elementId);
m = new AddTransactionMove(fp, t );
tempList.add(m);
} else {
assert (lkey.getType() == EndPoint);
Integer newSize = (Integer) worldDiffs.getDiff(lkey);
int oldSize = world.getNumberOfTransactions(fp);
if (newSize < oldSize) {
throw new UnsupportedOperationException();
}
}
break;
}
case ACTIVITY_LISTS:{
int playerId = lkey.getIndex()[0];
FreerailsPrincipal fp = worldDiffs.getPlayer(playerId)
.getPrincipal();
Object o = worldDiffs.getDiff(lkey);
logger.fine(lkey.toString() + " --> "+ o.toString());
switch (lkey.getIndex().length){
case 1:{
assert (lkey.getType() == EndPoint);
//Do nothing. Adding the activities will increase the
//size of the list.
break;
}
case 2:
assert (lkey.getType() == EndPoint);
//Do nothing. Adding the activities will increase the
//size of the list.
break;
case 3:{
Move m;
//Do we need to add a new active entity?
int entityId = lkey.getIndex()[1];
ActivityAndTime aat = (ActivityAndTime) worldDiffs.getDiff(lkey);
Activity act = aat.act;
int activityID = lkey.getIndex()[2];
if(entityId >= world.getNumberOfActiveEntities(fp) && 0 == activityID){
logger.fine("AddActiveEntityMove: "+act+" entityId="+entityId);
m = new AddActiveEntityMove(act, entityId, fp );
}else{
logger.fine("NextActivityMove: "+act+" entityId="+entityId);
m = new NextActivityMove(act,entityId, fp);
}
tempList.add(m);
break;
}default:
throw new UnsupportedOperationException(listId.toString());
}
break;
}
default:
throw new UnsupportedOperationException(listId.toString());
}
}
listChanges = new CompositeMove(tempList);
}

renderTile

Class: jfreerails.client.top.SimpleTileRenderer

Documentation

/**
* Renders a tile at the specified screen coordinates using the given world coordinates.
*
* @param g The Graphics object used for rendering.
* @param renderX The x-coordinate on the screen where the tile is rendered.
* @param renderY The y-coordinate on the screen where the tile is rendered.
* @param mapX The x-coordinate in the world map corresponding to the tile.
* @param mapY The y-Coordinate in the world map corresponding to the tile.
* @param w The ReadOnlyWorld instance providing tile data or image information.
*/

Source Code

public void renderTile(Graphics g, int renderX, int renderY, int mapX,
int mapY, ReadOnlyWorld w) {
g.drawImage(i, renderX, renderY, null);
}

Called Methods

No outgoing method calls

showBalanceSheet

Class: jfreerails.client.view.DialogueBoxController

Documentation

/**
* Displays the balance sheet by creating and configuring a BalanceSheetHtmlJPanel,
* then showing the content within the dialogue box.
*/

Source Code

public void showBalanceSheet() {
BalanceSheetHtmlJPanel bs = new BalanceSheetHtmlJPanel();
bs.setup(this.modelRoot, vl, this.closeCurrentDialogue);
this.showContent(bs);
}

start

Class: jfreerails.launcher.GUIClient

Documentation

/**
* Initializes and starts the game by setting up the server, connecting to it,
* creating a new game, and launching the game loop.
*
* This method performs the following steps:
* 1. Sets up the game world and initializes the saved games manager.
* 2. Creates and configures the FreerailsGameServer with the game model.
* 3. Connects to the server using the provided name and password.
* 4. Starts a new game with the selected map.
* 5. Waits for the world to be initialized and updates the game state.
* 6. Launches the game loop in a separate thread to handle ongoing updates.
*/

Source Code

void start() {
// Set up world.
SavedGamesManager gamesManager = new SavedGamesManagerImpl();
FreerailsGameServer server = new FreerailsGameServer(gamesManager);
String mapName = gamesManager.getNewMapNames()[0];
ServerGameModelImpl serverGameModel = new ServerGameModelImpl();
server.setServerGameModel(serverGameModel);
this.connect(server, name, "password");
server.newGame(mapName);
while (null == this.getWorld()) {
this.update();
server.update();
}
GameModel[] models = new GameModel[] { this, server };
// Start the game loop
GameLoop gameLoop = new GameLoop(screenHandler, models);
Thread t = new Thread(gameLoop);
t.start();
}

getSupply

Class: jfreerails.world.station.StationModel

Documentation

/**
* Returns the SupplyAtStation object representing the supply associated with this station.
*
* @return the SupplyAtStation instance associated with the station.
*/

Source Code

public SupplyAtStation getSupply() {
return supply;
}

Called Methods

No outgoing method calls

refreshTile

Class: jfreerails.client.renderer.TerrainLayer

Documentation

/**
* Refreshes the tile located at the specified coordinates (x, y).
* This method updates the tile's state or appearance to reflect any changes.
*
* @param x the x-coordinate of the tile to refresh
* @param y the y-coordinate of the tile to refresh
*/

Source Code

public void refreshTile(int x, int y) {
}

Called Methods

No outgoing method calls

removeOrder

Class: jfreerails.world.train.MutableSchedule

Documentation

/**
* Removes the order at the specified position.
*/

Source Code

/**
* Removes the order at the specified position.
*/
public void removeOrder(int orderNumber) {
if (PRIORITY_ORDERS == orderNumber && hasPriorityOrders) {
// If we are removing the priority stop.
hasPriorityOrders = false;
}
orders.remove(orderNumber);
/* shift current station down */
if (nextScheduledOrder > orderNumber) {
nextScheduledOrder--;
}
if (orders.size() <= nextScheduledOrder) {
nextScheduledOrder = firstScheduleStop();
}
if (0 == numberOfScheduledStops()) {
nextScheduledOrder = -1;
}
}

dumpImages

Class: jfreerails.client.renderer.SpecialTileRenderer

Documentation

/**
* Sets the image for this tile renderer using the generated filename and the first tile icon.
* This method delegates to {@link ImageManager#setImage(String, java.awt.Image)} to associate
* the generated filename with the tile's primary icon.
*
* @param imageManager The image manager responsible for handling image resources.
*
* @see #generateFilename()
* @see #getTileIcons()
*/

Source Code

@Override
public void dumpImages(ImageManager imageManager) {
imageManager.setImage(generateFilename(), this.getTileIcons()[0]);
}

equals

Class: jfreerails.world.cargo.MutableCargoBundle

Documentation

/**
* Compares this MutableCargoBundle instance with the specified object for equality.
* This method first checks if the object is null or not an instance of CargoBundle,
* returning false in such cases. If both conditions are satisfied, it delegates the
* equality check to the {@code equals} method of {@code ImmutableCargoBundle},
* comparing this bundle with the provided CargoBundle instance.
*
* @param arg0 the object to compare with this instance
* @return true if the objects are considered equal, false otherwise
*/

Source Code

@Override
public boolean equals(Object arg0) {
if (null == arg0) {
return false;
}
if (!(arg0 instanceof CargoBundle)) {
return false;
}
return ImmutableCargoBundle.equals(this, (CargoBundle) arg0);
}

getPosition

Class: jfreerails.controller.FlatTrackExplorer

Documentation

/**
* Returns the integer representation of the current position on the track.
* This method delegates to the {@code toInt()} method of the
* {@code PositionOnTrack} class to convert the current position to an integer.
*
* @return the integer value of the current position on the track
*/

Source Code

public int getPosition() {
return this.currentPosition.toInt();
}

showTerrainInfo

Class: jfreerails.client.view.DialogueBoxController

Documentation

/**
* Updates the terrain information with the specified terrain type and displays the content.
*
* @param terrainType  The type of terrain to be displayed, represented as an integer.
* @see jfreerails.client.view.TerrainInfoJPanel#setTerrainType(int)
* @see jfreerails.client.view.DialogueBoxController#showContent(Object)
*/

Source Code

public void showTerrainInfo(int terrainType) {
this.terrainInfo.setTerrainType(terrainType);
showContent(terrainInfo);
}

setServerPortPanelVisible

Class: jfreerails.launcher.SelectMapJPanel

Documentation

/**
* Sets the visibility of the server port panel.
*
* @param b  {@code true} to show the server port panel, {@code false} to hide it
*/

Source Code

void setServerPortPanelVisible(boolean b) {
this.jPanel3.setVisible(b);
}

Called Methods

No outgoing method calls

testCalExpense

Class: jfreerails.client.view.IncomeStatementGeneratorTest

Documentation

/**
* Tests the {@code calRevenue} method of the balance sheet generator to ensure
* it correctly calculates revenue based on the specified category.
* <p>
* This test performs the following steps:
* 1. Verifies that the initial revenue for the "Mail" category is zero.
* 2. Adds two transactions: one for the "Mail" category and another for "Passengers".
* 3. Confirms that the revenue for the "Mail" category matches the expected amount
*    after the transactions are processed.
*
* @param balanceSheetGenerator The instance of the balance sheet generator
*                               under test.
* @param w The world context used to retrieve cargo type information.
*/

Source Code

public void testCalExpense() {
Categories mail = Categories.Mail;
Money m = balanceSheetGenerator.calRevenue(mail);
assertEquals(0, m.getAmount());
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, 0);
assertEquals(mail, ct.getCategory());
Money amount = new Money(100);
addTrans(mail, amount);
addTrans(Categories.Passengers, amount);
m = balanceSheetGenerator.calRevenue(mail);
assertEquals(amount, m);
}

getStatus

Class: jfreerails.controller.TrackPathFinder

Documentation

/**
* Returns the current status of the path finding algorithm.
* This method delegates the request to the underlying
* {@link jfreerails.controller.SimpleAStarPathFinder} instance
* to retrieve the status of the path finding operation.
*
* @return an integer representing the current status of the path finder.
*/

Source Code

public int getStatus() {
return pathFinder.getStatus();
}

getDisplayName

Class: jfreerails.world.terrain.TerrainType

Documentation

/**
* Returns the display name of this terrain type, which is used for user interface purposes or identification.
*
* @return the human-readable name of the terrain type
*/

Source Code

String getDisplayName();

Called Methods

No outgoing method calls

toPoint

Class: jfreerails.world.common.ImPoint

Documentation

/**
* Converts this ImPoint instance to a Point object with the same coordinates.
*
* @return a new Point instance with the same x and y values as this ImPoint.
*/

Source Code

public Point toPoint() {
return new Point(x, y);
}

Called Methods

No outgoing method calls

getStationToGoto

Class: jfreerails.world.train.ImmutableSchedule

Documentation

/**
* Returns the station ID that the train is ordered to go to.
* Returns -1 if there is no such order.
*
* @return the station ID of the order to go to, or -1 if no such order exists
*/

Source Code

public int getStationToGoto() {
int orderToGoto = getOrderToGoto();
if (-1 == orderToGoto) {
return -1;
}
TrainOrdersModel order = orders.get(orderToGoto);
return order.getStationID();
}

getPath

Class: jfreerails.world.train.TrainMotion

Documentation

/**
* Returns the current path that the train is following.
* This method provides access to the internal path representation
* which details the route the train is taking across tiles.
*
* @return the PathOnTiles object representing the train's current path
*/

Source Code

public PathOnTiles getPath() {
return path;
}

Called Methods

No outgoing method calls

start_Terrain_Types

Class: jfreerails.server.parser.CargoAndTerrainHandler

Documentation

/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/

Source Code

/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/
public void start_Terrain_Types(final Attributes meta) throws SAXException;

Called Methods

No outgoing method calls

HtmlJPanel

Class: jfreerails.client.view.HtmlJPanel

Documentation

/**
* Constructs a new HtmlJPanel with the specified HTML content.
*
* @param html the HTML content to be displayed in the panel
*
* This constructor initializes the panel's components by calling
* {@link #initComponents()} and then sets the HTML content using
* {@link #setHtml(String)}.
*/

Source Code

public HtmlJPanel(String html) {
initComponents();
setHtml(html);
}

getTrainId

Class: jfreerails.world.accounts.DeliverCargoReceipt

Documentation

/**
* Returns the ID of the train associated with this cargo receipt.
*
* @return the train ID as an integer.
*/

Source Code

public int getTrainId() {
return trainId;
}

Called Methods

No outgoing method calls

isOpen

Class: jfreerails.network.Connection2Server

Documentation

/** Returns true if this connection is open. */

Source Code

/** Returns true if this connection is open. */
boolean isOpen();

Called Methods

No outgoing method calls

startDocument

Class: jfreerails.server.parser.Track_TilesParser

Documentation

/**
* Called when the parsing of a document starts.
* Initializes any necessary state or resources required for parsing the track tiles data.
*
* @throws SAXException if an error occurs during document initialization.
*/

Source Code

public void startDocument() throws SAXException {
}

Called Methods

No outgoing method calls

testChangingElementInList2

Class: jfreerails.move.WorldDiffsMoveTest

Documentation

/**
* Tests changing elements in a list by adding two cities to the world's STATIONS list,
* then modifying the diffs to change those entries to city2. Verifies that the diffs
* count is 2 and that the generated WorldDiffMove also has two diffs.
*/

Source Code

public void testChangingElementInList2() {
world.add(fp1, KEY.STATIONS, city1);
world.add(fp1, KEY.STATIONS, city1);
diffs.set(fp1, KEY.STATIONS, 0, city2);
diffs.set(fp1, KEY.STATIONS, 1, city2);
assertEquals(2, diffs.listDiffs());
WorldDiffMove move = WorldDiffMove.generate(diffs, WorldDiffMove.Cause.Other);
assertEquals(2, move.listDiffs());
}

endInMiddleOfSegment

Class: jfreerails.world.train.PathWalkerImpl

Documentation

/**
* Updates the end point coordinates (x2, y2) of the provided line segment
* to reflect the position where the movement ended in the middle of the current segment.
* This method adjusts the line's end point based on the accumulated distance along the segment.
*
* @param line The line segment whose end point (x2, y2) is to be updated
*             to represent the position where the movement ended.
*/

Source Code

private void endInMiddleOfSegment(IntLine line) {
distanceAlongCurrentSegment += distanceOfThisStepRemaining;
distanceOfThisStepRemaining = 0;
line.x2 = getCoordinateOnSegment(distanceAlongCurrentSegment,
currentSegment.x1, currentSegment.x2);
line.y2 = getCoordinateOnSegment(distanceAlongCurrentSegment,
currentSegment.y1, currentSegment.y2);
}

LogOnRequest

Class: jfreerails.network.specifics.LogOnRequest

Documentation

/**
* Constructs a new LogOnRequest object with the specified username and password.
*
* @param username The username of the user attempting to log on.
* @param password The password associated with the user's account.
*/

Source Code

public LogOnRequest(String username, String password) {
this.username = username;
this.password = password;
}

Called Methods

No outgoing method calls

getTerrainTypeID

Class: jfreerails.world.track.FreerailsTile

Documentation

/**
* Returns the terrain type ID of this tile.
* The terrain type ID is an integer that represents the type of terrain
* present on this tile in the game world.
*
* @return the terrain type ID as an integer
*/

Source Code

public int getTerrainTypeID() {
return terrainType;
}

Called Methods

No outgoing method calls

processMessage

Class: jfreerails.network.specifics.FreerailsClient

Documentation

/** Processes a message received from the server. */

Source Code

/** Processes a message received from the server. */
final void processMessage(FreerailsSerializable message) throws IOException {
if (message instanceof Message2Client) {
Message2Client request = (Message2Client) message;
MessageStatus status = request.execute(this);
logger.fine(request.toString());
connection2Server.writeToServer(status);
} else if (message instanceof Move) {
Move m = (Move) message;
committer.fromServer(m);
moveFork.processMove(m);
} else if (message instanceof MoveStatus) {
MoveStatus ms = (MoveStatus) message;
committer.fromServer(ms);
} else if (message instanceof PreMove) {
PreMove pm = (PreMove) message;
Move m = committer.fromServer(pm);
moveFork.processMove(m);
} else if (message instanceof PreMoveStatus) {
PreMoveStatus pms = (PreMoveStatus) message;
committer.fromServer(pms);
} else {
logger.fine(message.toString());
}
}

reverse

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

/**
* Returns a new TrainPositionOnMap instance with the coordinates reversed.
* This method creates a new TrainPositionOnMap object where the xpoints and ypoints
* arrays are reversed in order, while preserving the speed, acceleration, and
* activity values from the original instance.
*
* @return A new TrainPositionOnMap instance representing the reversed position.
*/

Source Code

public TrainPositionOnMap reverse() {
int length = xpoints.size();
int[] reversed_xpoints = new int[length];
int[] reversed_ypoints = new int[length];
for (int i = 0; i < length; i++) {
reversed_xpoints[i] = xpoints.get(length - i - 1);
reversed_ypoints[i] = ypoints.get(length - i - 1);
}
return new TrainPositionOnMap(reversed_xpoints, reversed_ypoints,
speed, acceleration, activity);
}

testGetSchedule

Class: jfreerails.controller.AddTrainPreMoveTest

Documentation

/**
* Tests the {@link AddTrainPreMove} class's ability to generate and execute a move
* that successfully creates a train target. This test verifies that the move sequence
* correctly initializes a train using the provided track path and schedule.
*
* The test sets up a world, constructs a move executor, builds a track path,
* generates a move via {@link AddTrainPreMove#generateMove}, and executes it.
* It then asserts that the resulting train target is not null.
*
* @throws IllegalStateException if any step in the move execution fails,
*         indicating an invalid move or setup.
*/

Source Code

public void testGetSchedule() {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
TrackMoveProducer producer = new TrackMoveProducer(me, world, mr);
Step[] trackPath = {EAST, SOUTH_EAST, SOUTH, SOUTH_WEST, WEST,
NORTH_WEST, NORTH, NORTH_EAST};
ImPoint from = new ImPoint(5, 5);
MoveStatus ms = producer.buildTrack(from, trackPath);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
TrainOrdersModel[] orders = {};
ImmutableSchedule is = new ImmutableSchedule(orders, -1, false);
AddTrainPreMove addTrain = new AddTrainPreMove(0, new ImInts(), from,
principal, is);
Move m = addTrain.generateMove(world);
ms = m.doMove(world, principal);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
TrainAccessor ta = new TrainAccessor(world, principal, 0);
assertNotNull(ta.getTarget());
}

equals

Class: jfreerails.network.specifics.NewGameMessage2Server

Documentation

/**
* Compares this {@code NewGameMessage2Server} object with the specified object for equality.
* Two objects are considered equal if they have the same {@code id} and {@code mapName}.
*
* @param o the object to compare with this instance
* @return true if the objects are equal, false otherwise
*/

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof NewGameMessage2Server))
return false;
final NewGameMessage2Server newGameMessage2Server = (NewGameMessage2Server) o;
if (id != newGameMessage2Server.id)
return false;
if (!mapName.equals(newGameMessage2Server.mapName))
return false;
return true;
}

Called Methods

No outgoing method calls

getDistance

Class: jfreerails.world.train.PathOnTiles

Documentation

/**
* Calculates the total distance covered by the first 'steps' steps in the path.
*
* @param steps the number of steps to include in the distance calculation.
* @return the accumulated distance from the first 'steps' steps.
*/

Source Code

public double getDistance(int steps) {
double distanceSoFar = 0;
for (int i = 0; i < steps; i++) {
Step v = vectors.get(i);
distanceSoFar += v.getLength();
}
return distanceSoFar;
}

setup

Class: jfreerails.client.view.SelectWagonsJPanel

Documentation

/**
* Initializes the UI components of the SelectWagonsJPanel by configuring
* the wagon types list model, cell renderer, and OK button action listener.
*
* @param mr The ModelRoot instance providing access to the world data.
* @param vl The RenderersRoot instance used for rendering wagon details.
* @param closeAction The Action to trigger when the OK button is clicked.
*/

Source Code

public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
World2ListModelAdapter w2lma = new World2ListModelAdapter(
mr.getWorld(), SKEY.CARGO_TYPES);
this.wagonTypesJList.setModel(w2lma);
this.rr = vl;
WagonCellRenderer wagonCellRenderer = new WagonCellRenderer(w2lma,
rr);
this.wagonTypesJList.setCellRenderer(wagonCellRenderer);
this.okjButton.addActionListener(closeAction);
}

paintTile

Class: jfreerails.client.renderer.BlankMapRenderer

Documentation

/**
* Paints a single tile at the specified tile coordinates using the provided graphics context.
* This method delegates the painting operation to {@link #paintRect(Graphics, java.awt.Shape)}
* by passing {@code null} as the shape parameter, which likely results in default rendering behavior.
*
* @param g      the graphics context used for rendering
* @param tileX  the x-coordinate of the tile to paint
* @param tileY  the y-coordinate of the tile to paint
*/

Source Code

public void paintTile(Graphics g, int tileX, int tileY) {
paintRect(g, null);
}

oKButtonActionPerformed

Class: jfreerails.client.view.SaveGameJPanel

Documentation

/**
* Handles the action event when the OK button is pressed.
* Retrieves the filename from the text field, saves the current game
* by setting the QUICK_MESSAGE property and sending a SaveGameMessage2Server
* command to the model. Also closes the panel.
*
* @param evt the ActionEvent triggered by the OK button action
* @throws Exception if an error occurs during property setting or command sending
*/

Source Code

private void oKButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_oKButtonActionPerformed
String filename = fileNameTextField.getText();
// Save the current game using the string
modelRoot.setProperty(Property.QUICK_MESSAGE, "Saved game "
+ filename);
Message2Server message2 = new SaveGameMessage2Server(1,
filename + ".sav");
modelRoot.sendCommand(message2);
close.actionPerformed(evt);
}//GEN-LAST:event_oKButtonActionPerformed

FlowRateInputStream

Class: jfreerails.util.FlowRateInputStream

Documentation

/**
* Initializes a new FlowRateInputStream with the specified input stream and stream name.
* This constructor uses default values for the flow rate parameters, which are 60 and 1000.
*
* @param in the underlying input stream to wrap
* @param streamName the name of the stream (used for logging or identification purposes)
*/

Source Code

public FlowRateInputStream(InputStream in, String streamName) {
this(in, streamName, 60, 1000);
}

setTrainViewHeight

Class: jfreerails.client.view.TrainListJPanel

Documentation

/**
* Sets the height of the train view.
*
* @param trainViewHeight the new height value for the train view
*/

Source Code

public void setTrainViewHeight(int trainViewHeight) {
this.trainViewHeight = trainViewHeight;
}

Called Methods

No outgoing method calls

waitForObjectFromServer

Class: jfreerails.network.Connection2Server

Documentation

/**
* Returns the next object read from the server, blocking if non is
* available.
*/

Source Code

/**
* Returns the next object read from the server, blocking if non is
* available.
*/
FreerailsSerializable waitForObjectFromServer() throws IOException,
InterruptedException;

Called Methods

No outgoing method calls

checkForNulls

Class: jfreerails.world.common.ImList

Documentation

/**
* Checks each element in the internal array for null values.
* If any element is found to be null, a NullPointerException is thrown.
*
* @throws NullPointerException if any element in the array is null.
*/

Source Code

public void checkForNulls() throws NullPointerException {
for (int i = 0; i < elementData.length; i++) {
if (null == elementData[i])
throw new NullPointerException();
}
}

Called Methods

No outgoing method calls

size

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

/**
* Returns the number of elements in the specified list.
*/

Source Code

/**
* Returns the number of elements in the specified list.
*/
int size(FreerailsPrincipal p, KEY key);

Called Methods

No outgoing method calls

toString

Class: jfreerails.world.player.PlayerPrincipal

Documentation

/**
* Overrides the toString method from the superclass to provide a string
* representation of the player principal. This method returns a formatted
* string that includes the player's ID.
*
* @return A string in the format "Player {id}", where {id} is the player's unique identifier.
*/

Source Code

@Override
public String toString() {
return "Player " + id;
}

Called Methods

No outgoing method calls

getUsername

Class: jfreerails.network.specifics.LogOnRequest

Documentation

/** Returns the username associated with this log-on request. @return the username */

Source Code

public String getUsername() {
return username;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.controller.MyDisplayMode

Documentation

/**
* Compares this MyDisplayMode instance with the specified object for equality.
* The comparison is based on the displayMode field.
*
* @param o the object to compare with
* @return true if the objects are equal, false otherwise
*/

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof MyDisplayMode) {
MyDisplayMode test = (MyDisplayMode) o;
return test.displayMode.equals(this.displayMode);
}
return false;
}

Called Methods

No outgoing method calls

gotoRow

Class: jfreerails.world.top.NonNullElements

Documentation

/**
* Moves the current row to the specified newRow by navigating through the sequence of elements.
* If the current row is already equal to newRow, this method has no effect.
* If newRow is greater than the current row, it advances to the target row using the {@code next()} method.
* If newRow is less than the current row, it moves backward to the target row using the {@code previous()} method.
*
* @param newRow the target row index to move to
*/

Source Code

public void gotoRow(int newRow) {
if (row == newRow) {
return;
}
if (row < newRow) {
while (row != newRow) {
next();
}
} else {
while (row != newRow) {
previous();
}
}
return;
}

changeStationActionPerformed

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

/**
* Handles the action event when the user selects a different station.
* Retrieves the selected order index from the orders component and triggers
* the station selection dialog using {@link #showSelectStation}.
*
* @param evt The ActionEvent object representing the user's interaction.
*            This parameter is not directly used in the method logic.
*/

Source Code

private void changeStationActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_changeStationActionPerformed
int orderNumber = this.orders.getSelectedIndex();
showSelectStation(this.getSchedule(), orderNumber);
}// GEN-LAST:event_changeStationActionPerformed

setRate

Class: jfreerails.controller.CargoElementObject

Documentation

/**
* Sets the rate for this cargo element.
*
* @param rate  The rate value to set.
*/

Source Code

public void setRate(int rate) {
this.rate = rate;
}

Called Methods

No outgoing method calls

ChangeTrainMove

Class: jfreerails.move.ChangeTrainMove

Documentation

/**
* Constructs a new ChangeTrainMove instance to represent a change in the list of trains.
* This move records the modification of a train at the specified index, replacing the previous state
* with the new state.
*
* @param index the index of the train in the list that is being modified
* @param before the FreerailsSerializable object representing the state of the train before the change
* @param after the FreerailsSerializable object representing the state of the train after the change
* @param p the FreerailsPrincipal associated with the user performing the change
*/

Source Code

private ChangeTrainMove(int index, FreerailsSerializable before,
FreerailsSerializable after, FreerailsPrincipal p) {
super(KEY.TRAINS, index, before, after, p);
}

testPathAsVectors2

Class: jfreerails.controller.PathOnTrackFinderTest

Documentation

/**
* Tests the pathAsVectors method to ensure it returns the correct path when a valid path is found.
* This test sets up a predefined path, calculates the end point, builds the track, and verifies
* that the search finds the path and the returned vectors match the expected steps.
*/

Source Code

public void testPathAsVectors2() {
Step[] path = { EAST, EAST, SOUTH_EAST, EAST, EAST, NORTH_EAST };
ImPoint start = new ImPoint(5, 5);
ImPoint end = Step.move(start, path);
producer.buildTrack(start, path);
try {
pathFinder.setupSearch(start, end);
pathFinder.search(-1);
assertEquals(IncrementalPathFinder.PATH_FOUND, pathFinder
.getStatus());
Step[] pathFound = pathFinder.pathAsVectors();
assertTrue(Arrays.equals(path, pathFound));
} catch (PathNotFoundException e) {
fail();
}
}

getH

Class: jfreerails.controller.GraphExplorer

Documentation

/**
* Returns the value of H associated with the current node or element in the graph exploration.
* The 'H' value represents a specific attribute or metric used during graph traversal or analysis.
*
* @return the integer value of H
*/

Source Code

int getH();

Called Methods

No outgoing method calls

StepTest

Class: jfreerails.world.common.StepTest

Documentation

/**
* Constructs a new StepTest instance with the specified argument.
*
* @param arg0 the input string used to initialize the StepTest object
*/

Source Code

public StepTest(String arg0) {
super(arg0);
}

Called Methods

No outgoing method calls

tryDoMove

Class: jfreerails.move.ChangeItemInListMove

Documentation

/**
* Attempts to perform the move operation by invoking the internal tryMove method.
* This method is responsible for executing the change of an item in a list within the game world.
*
* @param w The current game world state used to apply the move.
* @param p The principal (user) associated with the move operation.
* @return The status of the move operation indicating success, failure, or partial success.
*/

Source Code

public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
return tryMove(after, before, w);
}

centerOnTile

Class: jfreerails.client.view.MapViewJComponent

Documentation

/**
* Centers the view on the specified tile coordinates.
*
* @param tile the tile coordinates to center the view on
*/

Source Code

public void centerOnTile(Point tile) {
float scale = getMapView().getScale();
Rectangle visRect = new Rectangle(this.getVisibleRect());
visRect.x = (int) (tile.x * scale - (visRect.width / 2));
visRect.y = (int) (tile.y * scale - (visRect.height / 2));
this.scrollRectToVisible(visRect);
}

setup

Class: jfreerails.client.view.ServerControlModel

Documentation

/**
* Initializes the instance by setting the root model and dialogue box controller,
* then registers this object as a property change listener for the model root.
*
* @param modelRoot The root model to which the listener is added.
* @param dbc The controller responsible for managing dialogue box interactions.
*/

Source Code

public void setup(ModelRootImpl modelRoot, DialogueBoxController dbc) {
this.modelRoot = modelRoot;
this.dbc = dbc;
modelRoot.addPropertyChangeListener(this);
}

hashCode

Class: jfreerails.world.terrain.CityModel

Documentation

/**
* Overrides the {@code hashCode} method from the {@code Object} class to generate a hash code
* based on the object's state. The hash code is computed using the {@code name}, {@code x}, and
* {@code y} fields, ensuring that objects with the same values for these fields produce the same
* hash code.
*
* @return the computed hash code for this object
*/

Source Code

@Override
public int hashCode() {
int result;
result = name.hashCode();
result = 29 * result + x;
result = 29 * result + y;
return result;
}

Called Methods

No outgoing method calls

setupWorld

Class: jfreerails.controller.MoveTrainPreMove1stTest

Documentation

/**
* Sets up the test world by initializing the map, building tracks and stations,
* configuring train orders, and preparing a pre-move action for a train.
* This method creates a terminal station at position (10,10), another station at (19,10),
* and configures a train with specific orders. It also verifies that all operations succeed.
*
* @throws Exception If any step in the setup fails, though assertions ensure success.
*/

Source Code

@Override
protected void setupWorld() {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
trackBuilder = new TrackMoveProducer(me, world, mr);
stationBuilder = new StationBuilder(me);
// Build track.
stationBuilder
.setStationType(stationBuilder.getTrackTypeID("terminal"));
Step[] track = { EAST, EAST, EAST, EAST, EAST, EAST, EAST, EAST, EAST };
stationA = new ImPoint(10, 10);
MoveStatus ms0 = trackBuilder.buildTrack(stationA, track);
assertTrue(ms0.ok);
// Build 2 stations.
MoveStatus ms1 = stationBuilder.buildStation(stationA);
assertTrue(ms1.ok);
stationB = new ImPoint(19, 10);
MoveStatus ms2 = stationBuilder.buildStation(stationB);
assertTrue(ms2.ok);
TrainOrdersModel order0 = new TrainOrdersModel(1, null, false, false);
TrainOrdersModel order1 = new TrainOrdersModel(0, null, false, false);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
defaultSchedule = s.toImmutableSchedule();
ImPoint start = new ImPoint(10, 10);
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0),
start, principal, defaultSchedule);
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, principal);
assertTrue(ms.ok);
}

sizeD2

Class: jfreerails.util.List2DDiff

Documentation

/**
* Returns the size of the specified dimension in the 2D list.
*
* @param d1 the dimension index (0 for the first dimension, 1 for the second)
* @return the size of the specified dimension
*/

Source Code

public int sizeD2(int d1) {
return super.size(d1);
}

TrainModel

Class: jfreerails.world.train.TrainModel

Documentation

/**
* Constructs a new TrainModel with the specified wagon types and cargo bundle ID.
*
* @param wagons      A map representing the types of wagons in the train.
* @param BundleId    The identifier for the cargo bundle associated with this train.
*
* @throws IllegalArgumentException if the wagons parameter is null or invalid.
*/

Source Code

public TrainModel(ImInts wagons, int BundleId) {
wagonTypes = wagons;
cargoBundleId = BundleId;
engineTypeId = 0;
scheduleId = 0;
}

Called Methods

No outgoing method calls

addDirtyRegion

Class: jfreerails.client.common.RepaintManagerForActiveRendering

Documentation

/**
* Overrides the addDirtyRegion method to determine whether to add a dirty region
* for repainting based on the component's ancestor hierarchy. If the component
* has a different ancestor (as determined by {@link #hasDifferentAncestor(JComponent)}),
* the superclass's method is called to add the dirty region. Otherwise, a repaint
* request counter is incremented.
*
* @param c the component for which the dirty region is being added
* @param x the x-coordinate of the top-left corner of the dirty region
* @param y the y-coordinate of the top-left corner of the dirty region
* @param w the width of the dirty region
* @param h the height of the dirty region
*/

Source Code

@Override
public synchronized void addDirtyRegion(JComponent c, int x, int y, int w,
int h) {
if (hasDifferentAncestor(c)) {
super.addDirtyRegion(c, x, y, w, h);
} else {
numRepaintRequests++;
}
}

set

Class: jfreerails.util.IntArray

Documentation

/**
* Set the value at an index position in the array.
*
* @param index
* index position to be set
* @param value
* value to be set
*/

Source Code

/**
* Set the value at an index position in the array.
*
* @param index
* index position to be set
* @param value
* value to be set
*/
public final void set(int index, int value) {
if (index < countPresent) {
baseArray[index] = value;
} else {
throw new ArrayIndexOutOfBoundsException("Invalid index value");
}
}

Called Methods

No outgoing method calls

addToHead

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

/**
* Adds the specified train position to the head of this train's position list.
* This method creates a new TrainPositionOnMap instance where the given position
* is placed at the head (front) of the sequence. The original position remains unchanged.
*
* @param b the TrainPositionOnMap instance to add to the head of this position
* @return a new TrainPositionOnMap instance with the specified position added to the head
*/

Source Code

public TrainPositionOnMap addToHead(TrainPositionOnMap b) {
TrainPositionOnMap a = this;
return addBtoHeadOfA(b, a);
}

stepForward

Class: jfreerails.world.train.PathWalker

Documentation

/**
* Moves this path walker forward by the specified distance along the path
* and returns a path iterator to retrieve the section of the path travelled
* during this move.
*/

Source Code

/**
* Moves this path walker forward by the specified distance along the path
* and returns a path iterator to retrieve the section of the path travelled
* during this move.
*/
void stepForward(double distance);

Called Methods

No outgoing method calls

trackPieceIsLegal

Class: jfreerails.world.track.TrackRule

Documentation

/**
* Checks whether the track piece configured in the given TrackConfiguration is legally placed
* according to the rules defined by this TrackRule subclass.
*
* @param config the configuration of the track piece to be validated
* @return true if the track piece is legally placed, false otherwise
*/

Source Code

boolean trackPieceIsLegal(TrackConfiguration config);

Called Methods

No outgoing method calls

suite

Class: jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest

Documentation

/**
* Constructs and returns a JUnit test suite for the
* {@link DropOffAndPickupCargoMoveGeneratorTest} class.
*
* @return A TestSuite instance containing all test cases for this class.
*/

Source Code

private static junit.framework.Test suite() {
junit.framework.TestSuite testSuite = new junit.framework.TestSuite(
DropOffAndPickupCargoMoveGeneratorTest.class);
return testSuite;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.move.WorldDiffMove

Documentation

/**
* Overrides the equals method to compare this WorldDiffMove object with another object.
* Returns true if the objects are the same instance, or if the compared object is an instance of WorldDiffMove
* and all corresponding fields (h, w, x, y, and diffs) are equal. The diffs are compared using the equals method
* from the jfreerails.world.common.ImList class.
*
* @param o the object to compare with
* @return true if the objects are equal, false otherwise
*/

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof WorldDiffMove))
return false;
final WorldDiffMove mapDiffMove = (WorldDiffMove) o;
if (h != mapDiffMove.h)
return false;
if (w != mapDiffMove.w)
return false;
if (x != mapDiffMove.x)
return false;
if (y != mapDiffMove.y)
return false;
if (!diffs.equals(mapDiffMove.diffs))
return false;
return true;
}

getNumberOfKeys

Class: jfreerails.world.top.SKEY

Documentation

/**
* Returns the number of keys (fields) defined in the SKEY class.
* This value is determined by counting the number of fields exposed by the SKEY class.
*
* @return the number of keys (fields) in the SKEY class
*/

Source Code

static int getNumberOfKeys() {
return SKEY.class.getFields().length;
}

Called Methods

No outgoing method calls

removeLastActivity

Class: jfreerails.world.top.World

Documentation

/**
* Removes the activity at the specified index from the list of activities
* associated with the given principal and returns the removed activity.
*
* @param principal the FreerailsPrincipal representing the user performing the action
* @param index the index of the activity to remove
* @return the Activity that was removed
*/

Source Code

Activity removeLastActivity(FreerailsPrincipal principal, int index);

Called Methods

No outgoing method calls

get

Class: jfreerails.util.List3D

Documentation

/**
* Retrieves the list at the specified indices in the 3D structure.
*
* @param d1 the index along the first dimension
* @param d2 the index along the second dimension
* @return the list at the specified positions in the 3D structure
*/

Source Code

List<T> get(int d1, int d2);

Called Methods

No outgoing method calls

createComingFrom

Class: jfreerails.world.common.PositionOnTrack

Documentation

/**
* Creates a new PositionOnTrack instance representing a position on the rail track.
* The direction parameter indicates the direction from which the position is approached.
*
* @param x the x-coordinate of the position on the track
* @param y the y-coordinate of the position on the track
* @param direction the Step enum value indicating the direction from which the position is coming
* @return a new PositionOnTrack instance with the specified coordinates and direction
*/

Source Code

public static PositionOnTrack createComingFrom(int x, int y, Step direction) {
return new PositionOnTrack(x, y, direction);
}

Called Methods

No outgoing method calls

testCreateInOppositeDirectionToPath

Class: jfreerails.world.train.TrainPositionOnMapTest

Documentation

/**
* Tests that reversing a TrainPositionOnMap created with createInSameDirectionAsPath
* results in the expected coordinates when the path is defined with specific points.
*/

Source Code

public void testCreateInOppositeDirectionToPath() {
FreerailsPathIterator path = new SimplePathIteratorImpl(new int[] { 40,
30, 20, 10 }, new int[] { 44, 33, 22, 11 });
TrainPositionOnMap a = TrainPositionOnMap.createInSameDirectionAsPath(
path).reverse();
assertEquals(a.getLength(), 4);
assertEquals(a.getX(3), 40);
assertEquals(a.getY(3), 44);
assertEquals(a.getX(2), 30);
assertEquals(a.getY(2), 33);
assertEquals(a.getX(1), 20);
assertEquals(a.getY(1), 22);
assertEquals(a.getX(0), 10);
assertEquals(a.getY(0), 11);
}

yearEnd

Class: jfreerails.server.ServerGameModelImpl

Documentation

/** This is called on the last tick of each year. */

Source Code

/** This is called on the last tick of each year. */
private void yearEnd() {
TrackMaintenanceMoveGenerator tmmg = new TrackMaintenanceMoveGenerator(
moveExecuter);
tmmg.update(world);
TrainMaintenanceMoveGenerator trainMaintenanceMoveGenerator = new TrainMaintenanceMoveGenerator(
moveExecuter);
trainMaintenanceMoveGenerator.update(world);
InterestChargeMoveGenerator interestChargeMoveGenerator = new InterestChargeMoveGenerator(
moveExecuter);
interestChargeMoveGenerator.update(world);
// Grow cities.
WorldDiffs wd = new WorldDiffs(world);
CityTilePositioner ctp = new CityTilePositioner(wd);
ctp.growCities();
WorldDiffMove move = new WorldDiffMove(world, wd, WorldDiffMove.Cause.YearEnd);
moveExecuter.processMove(move);
}

getUpdatedTiles

Class: jfreerails.move.ChangeTileMove

Documentation

/**
* Returns the rectangle representing the single tile that has been updated by this move.
*
* @return the Rectangle object representing the updated tile's position and size (1x1).
*/

Source Code

public Rectangle getUpdatedTiles() {
Rectangle r = new Rectangle(x, y, 1, 1);
return r;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.track.LegalTrackConfigurations

Documentation

/**
* Compares this LegalTrackConfigurations object with the specified object for equality.
* Two LegalTrackConfigurations objects are considered equal if they have the same maximum
* consecutive pieces value and their legal configurations sets are equal.
*
* @param o the object to compare with
* @return true if the objects are equal, false otherwise
*/

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof LegalTrackConfigurations) {
LegalTrackConfigurations test = (LegalTrackConfigurations) o;
if (this.maximumConsecutivePieces == test
.getMaximumConsecutivePieces()
&& this.legalConfigs.equals(test.legalConfigs)) {
return true;
}
return false;
}
return false;
}

getId

Class: jfreerails.controller.MessageStatus

Documentation

/** Returns the id of the command whose status this object stores. */

Source Code

/** Returns the id of the command whose status this object stores. */
public int getId() {
return id;
}

Called Methods

No outgoing method calls

mouseClicked

Class: jfreerails.client.view.MainMapAndOverviewMapMediator

Documentation

/**
* Handles mouse click events on the overview map. Converts the click coordinates
* to the corresponding position on the main map based on their relative sizes,
* scrolls the main map to that position, and triggers an update of the internal
* state via the {@code updateInside} method.
*
* @param evt the mouse event triggered by the user's click on the overview map
*/

Source Code

@Override
public void mouseClicked(MouseEvent evt) {
/*
* Rectangle r= overviewMapJPanel.mainMapVisibleRect;
* r.x=evt.getX()-r.width/2; r.y=evt.getY()-r.width/2;
*/
// float overviewScale=overviewMapJPanel.getScale();
// float mainMapScale=mainMap.getScale();
int overviewScale = overviewMapJPanel.getPreferredSize().width;
int mainMapScale = mainMap.getWidth();
int x = (evt.getX() * mainMapScale / overviewScale);
int y = (evt.getY() * mainMapScale / overviewScale);
Rectangle r = mainMap.getVisibleRect();
r.x = x - r.width / 2;
r.y = y - r.height / 2;
mainMap.scrollRectToVisible(r);
updateInside(evt);
}

testGetPoint

Class: jfreerails.world.train.PathOnTilesTest

Documentation

/**
* Tests the getPoint method of the PathOnTiles class to ensure it correctly
* returns the expected ImPoint at various steps along the path.
*/

Source Code

public void testGetPoint() {
ImPoint start = new ImPoint();
Step[] vectors = new Step[] { EAST, EAST, EAST };
PathOnTiles path = new PathOnTiles(start, vectors);
ImPoint expected = new ImPoint(15, 15);
ImPoint actual = path.getPoint(0);
assertEquals(expected, actual);
expected = new ImPoint(45, 15);
actual = path.getPoint(30);
assertEquals(expected, actual);
expected = new ImPoint(60, 15);
actual = path.getPoint(45);
assertEquals(expected, actual);
}

CompositeSpeedAgainstTime

Class: jfreerails.world.train.CompositeSpeedAgainstTime

Documentation

/**
* Constructs a CompositeSpeedAgainstTime by aggregating multiple
* {@link jfreerails.world.train.SpeedAgainstTime} instances.
*
* @param accs an array of {@link jfreerails.world.train.SpeedAgainstTime}
*             objects to be combined into a composite speed-time profile.
*             Null values in the array will trigger a null check via
*             {@link jfreerails.world.common.ImList#checkForNulls()}.
*
* @throws NullPointerException if any element in the {@code accs} array is null.
*/

Source Code

public CompositeSpeedAgainstTime(SpeedAgainstTime... accs) {
values = new ImList<SpeedAgainstTime>(accs);
values.checkForNulls();
double tempDuration = 0, tempTotalDistance = 0;
for (int i = 0; i < accs.length; i++) {
tempDuration += accs[i].getT();
tempTotalDistance += accs[i].getS();
}
finalT = tempDuration;
finalS = tempTotalDistance;
}

createBuildMenu

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

/**
* Creates and returns the "Build" menu used in the GUI for building operations.
*
* @return the JMenu instance representing the Build menu
*/

Source Code

public JMenu createBuildMenu() {
return buildMenu;
}

Called Methods

No outgoing method calls

initComponents

Class: jfreerails.client.view.StationInfoJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jLabel1 = new javax.swing.JLabel();
nextStation = new javax.swing.JButton();
previousStation = new javax.swing.JButton();
close = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
setMinimumSize(new java.awt.Dimension(250, 177));
jLabel1.setFont(new java.awt.Font("Dialog", 0, 10));
jLabel1
.setText("<html>\n<h4 align=\"center\">Supply and Demand at stationName</h4>\n<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"2\">\n <tr>\n <td>&nbsp;</td>\n <td>Will pay<br>for</td>\n <td>Supplies<br>(cars per year)</td>\n <td>Waiting for pickup<br>(car loads)</td>\n </tr>\n <tr>\n <td>Mail</td>\n <td>Yes</td>\n <td>&nbsp;</td>\n <td>&nbsp;</td>\n </tr>\n <tr>\n <td>Passengers</td>\n <td>No</td>\n <td>3</td>\n <td>2.5</td>\n </tr>\n \n</table>\n\n</html>");
jLabel1.setVerticalAlignment(javax.swing.SwingConstants.TOP);
jLabel1.setAlignmentY(0.0F);
jLabel1.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 4, 8);
add(jLabel1, gridBagConstraints);
nextStation.setText("next ->");
nextStation.setMargin(new java.awt.Insets(0, 0, 0, 0));
nextStation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextStationActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(nextStation, gridBagConstraints);
previousStation.setText("<- previous");
previousStation.setMargin(new java.awt.Insets(0, 0, 0, 0));
previousStation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
previousStationActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(previousStation, gridBagConstraints);
close.setText("close");
close.setMargin(new java.awt.Insets(0, 0, 0, 0));
close.setMaximumSize(new java.awt.Dimension(65, 22));
close.setMinimumSize(new java.awt.Dimension(65, 22));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
add(close, gridBagConstraints);
}// GEN-END:initComponents

stopAtStation

Class: jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest

Documentation

/**
* Tests the generation of a move for stopping at a station.
* Creates an instance of {@code DropOffAndPickupCargoMoveGenerator},
* generates a move, and verifies that the move execution results in
* {@code MoveStatus.MOVE_OK}.
*
* @param w The world state used for move execution (assumed to be an instance variable).
*/

Source Code

private void stopAtStation() {
DropOffAndPickupCargoMoveGenerator moveGenerator = new DropOffAndPickupCargoMoveGenerator(
0, 0, w, MapFixtureFactory.TEST_PRINCIPAL, false, false);
Move m = moveGenerator.generateMove();
if(null != m){
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
assertEquals(MoveStatus.MOVE_OK, ms);
}
}

setPosition

Class: jfreerails.controller.Map

Documentation

/**
* Sets the position of the map to the specified integer value and resets the branch to -1.
*
* @param i the new position value to set
*/

Source Code

public void setPosition(int i) {
this.position = i;
this.branch = -1;
}

Called Methods

No outgoing method calls

testPickUpCargo3

Class: jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest

Documentation

/**
* Tests that a train takes into account how much cargo it already has and
* the type of wagons it has when it is picking up cargo.
*/

Source Code

/**
* Tests that a train takes into account how much cargo it already has and
* the type of wagons it has when it is picking up cargo.
*/
public void testPickUpCargo3() {
ImInts wagons = new ImInts(0, 0, 2, 2);
// 2 wagons for cargo type 0; 2 wagons for cargo type 2.
addWagons(wagons);
// Set cargo on train.
setCargoOnTrain(this.cargoType0FromStation2, 30);
// Set cargo at station.
setCargoAtStation(this.cargoType0FromStation0, 110);
// Check that station does not demand cargo type 0.
StationModel station = (StationModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
0);
assertFalse(station.getDemand().isCargoDemanded(0));
// Stop at station.
stopAtStation();
/*
* The train has 2 wagons for cargo type 0 but had 30 units of cargo
* type 0 before stopping so it can only pick up 50 units.
*/
MutableCargoBundle expectedAtStation = new MutableCargoBundle();
expectedAtStation.setAmount(cargoType0FromStation0, 60);
MutableCargoBundle expectedOnTrain = new MutableCargoBundle();
expectedOnTrain.setAmount(this.cargoType0FromStation2, 30);
expectedOnTrain.setAmount(this.cargoType0FromStation0, 50);
assertEquals(expectedAtStation.toImmutableCargoBundle(),
getCargoAtStation());
assertEquals(expectedOnTrain.toImmutableCargoBundle(),
getCargoOnTrain());
}

itemAdded

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

/**
* Handles the addition of an item, updating the count of trains or stations
* based on the provided key and principal. This method is invoked when an item
* is added to the model, and it triggers the corresponding count method
* (countTrains() or countStations()) if the key matches and the principal
* matches the model's principal.
*
* @param key       The type of item being added (e.g., TRAINS or STATIONS).
* @param index     The index at which the item was added.
* @param principal The principal associated with the item addition.
*/

Source Code

public void itemAdded(KEY key, int index, FreerailsPrincipal principal) {
boolean rightPrincipal = principal
.equals(this.modelRoot.getPrincipal());
if (KEY.TRAINS == key && rightPrincipal) {
countTrains();
} else if (KEY.STATIONS == key && rightPrincipal) {
countStations();
}
}

getId

Class: jfreerails.controller.TrainAccessor

Documentation

/**
* Returns the unique identifier of this train accessor.
*
* @return the unique identifier of the train accessor
*/

Source Code

public int getId() {
return id;
}

Called Methods

No outgoing method calls

testGotoIndex

Class: jfreerails.world.top.NonNullElementsTest

Documentation

/**
* Tests the {@link WorldIterator#gotoIndex(int)} method to ensure it correctly
* navigates to the specified index, updates the row ID, and throws
* {@link NoSuchElementException} for invalid indices.
*/

Source Code

public void testGotoIndex() {
WorldIterator wi = new NonNullElements(KEY.STATIONS, w,
MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(WorldIterator.BEFORE_FIRST, wi.getRowID());
assertEquals(WorldIterator.BEFORE_FIRST, wi.getIndex());
wi.gotoIndex(2);
assertEquals(2, wi.getIndex());
assertEquals(1, wi.getRowID());
try {
wi.gotoIndex(100);
assertTrue(false);
} catch (NoSuchElementException e) {
}
}

dumpImages

Class: jfreerails.client.renderer.StandardTileRenderer

Documentation

/**
* Dumps the tile's image by generating a filename and setting it via the provided ImageManager.
* This method uses {@link #generateFilename()} to determine the filename and retrieves the first tile icon
* from {@link #getTileIcons()} to associate with the image.
*
* @param imageManager The ImageManager responsible for handling image operations.
*/

Source Code

@Override
public void dumpImages(ImageManager imageManager) {
imageManager.setImage(generateFilename(), this.getTileIcons()[0]);
}

CitySAXParser

Class: jfreerails.server.CitySAXParser

Documentation

/**
* Initializes a new CitySAXParser with the specified world instance.
*
* @param w the World instance to be associated with this parser
* @throws SAXException if an error occurs during parsing initialization
*/

Source Code

public CitySAXParser(World w) throws SAXException {
world = w;
cities = new Vector<CityModel>();
}

Called Methods

No outgoing method calls

addTrans

Class: jfreerails.client.view.IncomeStatementGeneratorTest

Documentation

/**
* Adds a transaction for a cargo type with the specified category.
* Iterates through all cargo types in the world, checks if their category
* matches the given category. If a match is found, creates a CargoBatch
* and adds a transaction using the specified amount and other parameters.
* If no matching category is found, throws an IllegalArgumentException.
*
* @param category  The category of the cargo type to which the transaction applies.
* @param amount    The monetary amount of the transaction.
* @throws IllegalArgumentException if no cargo type matches the specified category.
*/

Source Code

private void addTrans(Categories category, Money amount) {
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, i);
if (ct.getCategory().equals(category)) {
CargoBatch cb = new CargoBatch(i, 0, 0, 0, 0);
w.addTransaction(MapFixtureFactory.TEST_PRINCIPAL,
new DeliverCargoReceipt(amount, 10, 0, cb, 1));
return;
}
}
throw new IllegalArgumentException(category.toString());
}

SynchronizedFlag

Class: jfreerails.network.SynchronizedFlag

Documentation

/**
* Constructs a new SynchronizedFlag with the specified open state.
*
* @param b the initial value for the 'isOpen' field, indicating whether the flag is open
*/

Source Code

public SynchronizedFlag(boolean b) {
this.isOpen = b;
}

Called Methods

No outgoing method calls

setTime

Class: jfreerails.world.top.WorldImpl

Documentation

/**
* Sets the current time for the world.
*
* @param t the new GameTime value to set as the current time
*/

Source Code

public void setTime(GameTime t) {
time = t;
}

Called Methods

No outgoing method calls

logoff

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

/**
* Logs off a player by removing their NameAndPassword entry from the currently logged-on collection.
*
* @param player the index of the player in the players list to be logged off
* @throws IndexOutOfBoundsException if the player index is out of bounds
*/

Source Code

public void logoff(int player) {
NameAndPassword np = players.get(player);
currentlyLoggedOn.remove(np);
}

Called Methods

No outgoing method calls

listUpdated

Class: jfreerails.network.specifics.SimpleServerGameModel

Documentation

/**
* Notifies that a list has been updated, providing details about the change.
* This method is called when a list item is modified, specifying the key of the
* updated item, its index in the list, and the principal (user context) associated
* with the update. The principal is used to validate access or determine user-specific
* behavior.
*
* @param key       The unique identifier of the list item that was updated.
* @param index     The position of the updated item within the list.
* @param principal The user principal associated with the update, used for access control.
*/

Source Code

public void listUpdated(KEY key, int index, FreerailsPrincipal principal) {
}

Called Methods

No outgoing method calls

setPosition

Class: jfreerails.controller.FlatTrackExplorer

Documentation

/**
* Sets the current position on the track based on the provided integer value.
* This method updates the internal position state and resets the {@code beforeFirst} flag to {@code true},
* indicating the start of a new position tracking sequence.
*
* @param i the integer value representing the track position to set
*/

Source Code

public void setPosition(int i) {
beforeFirst = true;
currentPosition.setValuesFromInt(i);
}

removeLast

Class: jfreerails.world.top.WorldImpl

Documentation

/**
* Removes the last element from the 3D list associated with the specified player and key.
*
* @param p the {@code FreerailsPrincipal} representing the player, used to determine the player index
* @param key the {@code KEY} object specifying the key identifier, used to retrieve the key ID
* @return the {@code FreerailsSerializable} object that was removed from the 3D list
*/

Source Code

public FreerailsSerializable removeLast(FreerailsPrincipal p, KEY key) {
int playerIndex = p.getWorldIndex();
return lists.removeLastD3(playerIndex, key.getKeyID());
}

pullUpJMenuItemActionPerformed

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

/**
* Handles the action event when the "Pull Up" menu item is selected.
* This method retrieves the current schedule, identifies the selected order index,
* moves the selected order up in the schedule using the {@code pullUp} method,
* sends an update to reflect the change via {@code sendUpdateMove}, and
* updates the selected index to reflect the new position.
*
* @param evt The {@code ActionEvent} triggered by selecting the menu item.
*/

Source Code

private void pullUpJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pullUpJMenuItemActionPerformed
MutableSchedule s = getSchedule();
int i = orders.getSelectedIndex();
s.pullUp(i);
sendUpdateMove(s);
orders.setSelectedIndex(i - 1);
}// GEN-LAST:event_pullUpJMenuItemActionPerformed

testStops3

Class: jfreerails.controller.MoveTrainPreMove2ndTest

Documentation

/**
* Test that when the train arrives at a scheduled station tile it stops,
* updates its schedule and transfers cargo and starts moving again.
*/

Source Code

/**
* Test that when the train arrives at a scheduled station tile it stops,
* updates its schedule and transfers cargo and starts moving again.
*/
public void testStops3() {
// Add cargo to station 2
addCargoAtStation(2, 800);
// Keep moving train until it reaches station 2
PositionOnTrack pot;
TrainMotion tm;
int x;
do {
tm = moveTrain();
pot = tm.getFinalPosition();
x = pot.getX();
} while (x < station2Location.x);
assertEquals(station2Location.x, x);
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
// The train should be heading for station 1.
TrainAccessor ta = new TrainAccessor(world, principal, 0);
Schedule schedule1 = ta.getSchedule();
assertEquals(0, schedule1.getOrderToGoto());
assertEquals(2, schedule1.getStationToGoto());
ImPoint expectedTarget = new ImPoint(station2Location.x, station2Location.y);
assertEquals(expectedTarget, ta.getTarget());
// The next train motion should represent the stop at the station.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station2Location.x, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(STOPPED_AT_STATION, tm.getActivity());
// The train should be heading for station 0.
Schedule schedule2 = ta.getSchedule();
assertFalse(schedule2.equals(schedule1));
assertEquals(1, schedule2.getOrderToGoto());
assertEquals(0, schedule2.getStationToGoto());
// 80 Units of cargo should have been transferred to the train!
CargoBundle onTrain = ta.getCargoBundle();
int amount = onTrain.getAmount(0);
assertEquals(80, amount);
// Then the train should continue.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station2Location.x - 1, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
}

getCursorPosition

Class: jfreerails.client.top.UserInputOnMapController

Documentation

/**
* Retrieves the current cursor position from the model.
* This method fetches the {@code CURSOR_POSITION} property from the model root,
* returning it as an {@code ImPoint}. If the property is {@code null}, a default
* {@code ImPoint} instance is returned instead.
*
* @return the cursor position as an {@code ImPoint}, or a default instance if the property is null
*/

Source Code

private ImPoint getCursorPosition() {
ImPoint point = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.CURSOR_POSITION);
// Check for null
point = null == point ? new ImPoint() : point;
return point;
}

setSize

Class: jfreerails.util.ListXDDiffs

Documentation

/**
* Updates the diffs map by either removing or adding a size entry based on the provided dimensions.
* If the current underlying size matches the specified size, the corresponding entry is removed.
* Otherwise, a new entry is added with the specified size.
*
* @param size   The new size value to set for the specified dimensions.
* @param dim    Variable-length argument array representing the dimensions used to identify the size key.
*/

Source Code

private void setSize(int size, int... dim) {
ListKey sizeKey = new ListKey(ListKey.Type.EndPoint, listID, dim);
if (getUnderlyingSize(dim) == size) {
diffs.remove(sizeKey);
} else {
diffs.put(sizeKey, new Integer(size));
}
}

main

Class: jfreerails.launcher.Launcher

Documentation

/**
* Runs the game.
*/

Source Code

/**
* Runs the game.
*/
public static void main(String args[]) {
//SynchronizedEventQueue.use();
// Let the user know if we are using a custom logging config.
String loggingProperties = System
.getProperty("java.util.logging.config.file");
if (null != loggingProperties) {
logger.info("Logging properties file: " + loggingProperties);
}
logger.fine("Started launcher.");
boolean quickstart = false;
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
if (QUICKSTART.equals(args[i]))
quickstart = true;
}
}
Launcher launcher = new Launcher(quickstart);
launcher.start(quickstart);
}

hashCode

Class: jfreerails.move.RemoveItemFromListMove

Documentation

/**
* Overrides the hashCode method to generate a hash code based on the object's state.
* The hash code is computed using the {@code item}, {@code listKey}, {@code index}, and {@code principal} fields.
* This ensures that objects with equal state produce the same hash code, adhering to the Object.hashCode contract.
*
* @return the computed hash code.
*/

Source Code

@Override
public int hashCode() {
int result;
result = (item != null ? item.hashCode() : 0);
result = 29 * result + listKey.hashCode();
result = 29 * result + index;
result = 29 * result + principal.hashCode();
return result;
}

Called Methods

No outgoing method calls

TimeTickPreMove

Class: jfreerails.controller.TimeTickPreMove

Documentation

/**
* Private constructor to prevent instantiation from outside the class.
* This class is intended to be used internally and not instantiated directly.
*/

Source Code

private TimeTickPreMove() {
}

Called Methods

No outgoing method calls

getAfter

Class: jfreerails.move.ListMove

Documentation

/**
* @return the new item or null if not any.
*/

Source Code

/**
* @return the new item or null if not any.
*/
FreerailsSerializable getAfter();

Called Methods

No outgoing method calls

getTransactionAndTimeStamp

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

/**
* Retrieves the transaction and game time associated with the specified principal and index.
*
* @param p the FreerailsPrincipal representing the user or entity making the transaction
* @param i the index or identifier used to locate the specific transaction
* @return a Pair containing the transaction and the corresponding game time
*/

Source Code

public Pair<Transaction, GameTime> getTransactionAndTimeStamp(
FreerailsPrincipal p, int i);

Called Methods

No outgoing method calls

ChangeTrainScheduleMove

Class: jfreerails.move.ChangeTrainScheduleMove

Documentation

/**
* Constructs a new {@code ChangeTrainScheduleMove} instance representing a change
* to a train schedule. This move encapsulates the transition from a previous
* schedule state to a new schedule state for a specific train.
*
* @param id the unique identifier of the train associated with the schedule
* @param before the immutable schedule state before the change
* @param after the immutable schedule state after the change
* @param p the principal (user or entity) initiating the schedule change
*/

Source Code

public ChangeTrainScheduleMove(int id, ImmutableSchedule before,
ImmutableSchedule after, FreerailsPrincipal p) {
super(KEY.TRAIN_SCHEDULES, id, before, after, p);
}

legalRectangleContains

Class: jfreerails.client.top.UserInputOnMapController

Documentation

/**
* Checks whether specified point is in legal rectangle.
*
* @param tryThisPoint ImPoint
* @return boolean
*/

Source Code

/**
* Checks whether specified point is in legal rectangle.
*
* @param tryThisPoint ImPoint
* @return boolean
*/
private boolean legalRectangleContains(ImPoint tryThisPoint) {
ReadOnlyWorld world = modelRoot.getWorld();
int width = world.getMapWidth();
int height = world.getMapHeight();
Rectangle legalRectangle = new Rectangle(0, 0, width, height);
return legalRectangle.contains(tryThisPoint.toPoint());
}

ImHashSet

Class: jfreerails.world.common.ImHashSet

Documentation

/**
* Constructs an ImHashSet containing all elements from the provided list.
*
* @param values the list of elements to be added to the hash set
*/

Source Code

public ImHashSet(List<E> values) {
this.hashSet = new HashSet<E>();
for (E e : values) {
hashSet.add(e);
}
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.util.Pair

Documentation

/**
* Compares this Pair object with the specified Pair object for equality.
* Two Pair objects are considered equal if both their elements are equal.
*
* @param other the Pair object to compare with
* @return true if the objects are equal, false otherwise
*/

Source Code

public boolean equals(Pair<A, B> other) {
if (this == other)
return true;
if (null == other)
return false;
return (e1.equals(other.e1) && e2.equals(other.e2));
}

Called Methods

No outgoing method calls

cancelButtonActionPerformed

Class: jfreerails.client.view.LoadGameJPanel

Documentation

/**
* Handles the action event triggered when the cancel button is pressed.
* If the {@code close} object is not null, this method delegates the action
* to the {@code close}'s actionPerformed method with the provided event.
*
* @param evt the {@code ActionEvent} triggered by the cancel button action
*/

Source Code

private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
if(null != close)
close.actionPerformed(evt);
}//GEN-LAST:event_cancelButtonActionPerformed

Called Methods

No outgoing method calls

skippedEntity

Class: jfreerails.server.parser.Track_TilesParser

Documentation

/**
* Callback method invoked when an XML entity is skipped during parsing.
*
* @param name The name of the XML entity that was skipped.
* @throws SAXException If an error occurs while handling the skipped entity.
*/

Source Code

public void skippedEntity(java.lang.String name) throws SAXException {
}

Called Methods

No outgoing method calls

MyDisplayMode

Class: jfreerails.controller.MyDisplayMode

Documentation

No documentation available

Source Code

public MyDisplayMode(DisplayMode displayMode) {
this.displayMode = displayMode;
}

Called Methods

No outgoing method calls

generateSideOnFilename

Class: jfreerails.client.renderer.TrainImages

Documentation

/**
* Generates the filename for a side-on view train image based on the provided train name.
*
* @param name the name of the train used to construct the filename
* @return the full path to the side-on image file, including the directory structure and .png extension
*/

Source Code

public static String generateSideOnFilename(String name) {
return "trains" + File.separator + "sideon" + File.separator + name
+ ".png";
}

Called Methods

No outgoing method calls

getOverheadHighlightImage

Class: jfreerails.client.renderer.TrainImages

Documentation

/**
* @param direction
* @return the image to render under the wagon/engine image
* when the train is selects/focused.
*/

Source Code

/**
* @param direction
* @return the image to render under the wagon/engine image
* when the train is selects/focused.
*/
public Image getOverheadHighlightImage(int direction, Highlight h) {
if(h == Highlight.FOCUSED)
return overheadFocusedImages[direction];
if(h == Highlight.SELECTED)
return overheadSelectedImages[direction];
return null;
}

Called Methods

No outgoing method calls

getStationId

Class: jfreerails.controller.TrainAccessor

Documentation

/**
* @return the id of the station the train is currently at, or -1 if no
* current station.
*
*/

Source Code

/**
* @return the id of the station the train is currently at, or -1 if no
* current station.
*
*/
public int getStationId(double time){
TrainMotion tm = findCurrentMotion(time);
PositionOnTrack pot = tm.getFinalPosition();
int x = pot.getX();
int y = pot.getY();
//loop thru the station list to check if train is at the same Point
// as
// a station
for (int i = 0; i < w.size(p, KEY.STATIONS); i++) {
StationModel tempPoint = (StationModel) w.get(p, KEY.STATIONS, i);
if (null != tempPoint && (x == tempPoint.x) && (y == tempPoint.y)) {
return i; // train is at the station at location tempPoint
}
}
return -1;
}

hashCode

Class: jfreerails.world.train.TrainModel

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = scheduleId;
result = 29 * result + engineTypeId;
result = 29 * result + cargoBundleId;
return result;
}

Called Methods

No outgoing method calls

ImStringList

Class: jfreerails.world.common.ImStringList

Documentation

No documentation available

Source Code

public ImStringList(String... strings) {
this.strings = strings.clone();
}

Called Methods

  • _Dummy_.__Array__.clone (external)

testGetF

Class: jfreerails.controller.OpenListTest

Documentation

/**
* Tests the functionality of the getF method to ensure it behaves as expected.
* This method is part of the test suite for the OpenList class and verifies
* the correctness of the getF operation under standard conditions.
*/

Source Code

public void testGetF() {
}

Called Methods

No outgoing method calls

add

Class: experimental.GenerateDependenciesXmlAndHtml

Documentation

/**
* Adds a single package name by converting it into a String array and delegating
* to the {@link #add(String[])} method.
*
* @param packageName  The name of the package to be added.
*/

Source Code

private void add(String packageName) {
add(new String[] { packageName });
}

bondInterestRates

Class: jfreerails.controller.FinancialDataGatherer

Documentation

/**
* Retrieves an array of bond interest rates.
* <p>
* This method is intended to gather bond interest rate data. The returned array
* contains interest rates for various bonds or time periods. The current
* implementation returns null as a placeholder; the actual implementation
* should populate and return the data.
*
* @return an array of integers representing bond interest rates, or null if
*         data is not yet available.
*/

Source Code

public int[] bondInterestRates() {
return null;
}

Called Methods

No outgoing method calls

moveForward

Class: jfreerails.controller.Map

Documentation

/**
* Moves the entity forward by updating its position to the vertex connected by the current edge.
* This method retrieves the connected vertex using {@link #getVertexConnectedByEdge()} and sets it as the new position via {@link #setPosition(Object)}.
*/

Source Code

public void moveForward() {
this.setPosition(this.getVertexConnectedByEdge());
}

hashCode

Class: jfreerails.controller.MyDisplayMode

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return displayMode.hashCode();
}

Called Methods

No outgoing method calls

testSendingPreMoves

Class: jfreerails.network.specifics.FreerailsClientWithLocalServerTest

Documentation

/** Tests sending premoves between client and server. */

Source Code

/** Tests sending premoves between client and server. */
public void testSendingPreMoves() {
try {
/* Set up and start a game with 2 clients. */
FreerailsClient client0 = new FreerailsClient();
LogOnResponse response0 = client0.connect(server, "client0",
"password");
assertTrue(response0.isSuccessful());
FreerailsClient client1 = new FreerailsClient();
LogOnResponse response1 = client1.connect(server, "client1",
"password");
assertTrue(response1.isSuccessful());
client0.update();
client1.update();
ImStringList mapNames = (ImStringList) client0
.getProperty(ClientProperty.MAPS_AVAILABLE);
Message2Server message2 = new NewGameMessage2Server(99, mapNames
.get(0));
client0.write(message2);
server.update();
client0.update();
client1.update();
/* Now try sending some premoves. */
Player player0 = client0.getWorld().getPlayer(0);
FreerailsPrincipal principal0 = player0.getPrincipal();
PreMove pm = TimeTickPreMove.INSTANCE;
World copyOfWorld = client0.getWorld().defensiveCopy();
assertEquals(copyOfWorld, client0.getWorld());
Move move = pm.generateMove(copyOfWorld);
MoveStatus status = move.doMove(copyOfWorld, principal0);
assertTrue(status.isOk());
client0.processPreMove(pm);
server.update();
PreMoveStatus reply = (PreMoveStatus) client0.read();
assertEquals(PreMoveStatus.PRE_MOVE_OK, reply);
client0.processMessage(reply);
server.update();
client0.update();
client1.update();
assertEquals(copyOfWorld, client0.getWorld());
assertEquals(copyOfWorld, client1.getWorld());
assertEquals(copyOfWorld, server.getCopyOfWorld());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}

hashCode

Class: jfreerails.world.station.StationModel

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = x;
result = 29 * result + y;
result = 29 * result + (name != null ? name.hashCode() : 0);
result = 29 * result + (supply != null ? supply.hashCode() : 0);
result = 29 * result + (demand != null ? demand.hashCode() : 0);
result = 29 * result + (converted != null ? converted.hashCode() : 0);
result = 29 * result + cargoBundleNumber;
result = 29 * result + production.size();
return result;
}

start_Types

Class: jfreerails.server.parser.CargoAndTerrainHandlerImpl

Documentation

/**
* This method is called when the XML parser encounters the start of the &lt;Types&gt; element.
* It is part of the process for parsing cargo and terrain types defined in the XML configuration.
* No action is required here as the actual processing of type definitions is handled by subsequent methods.
*
* @param meta The attributes of the &lt;Types&gt; XML element, which may contain metadata about the types.
* @throws SAXException If an error occurs during XML parsing while processing the &lt;Types&gt; element.
*
* @see CargoAndTerrainHandler
* @see CargoAndTerrainParser
*/

Source Code

public void start_Types(final Attributes meta) throws SAXException {
// no need to do anything here.
}

Called Methods

No outgoing method calls

ImSet

Class: jfreerails.world.common.ImSet

Documentation

No documentation available

Source Code

public ImSet(Set<E> data) {
hashSet = new HashSet<E>(data);
}

Called Methods

No outgoing method calls

mouseReleased

Class: jfreerails.client.view.MainMapAndOverviewMapMediator

Documentation

/**
* Ends the drag operation by resetting the dragging state flag.
* This method is called when a mouse button is released, indicating
* that the drag interaction has concluded.
*
* @param evt The MouseEvent that triggered this method, providing
*            details about the mouse release action.
*/

Source Code

@Override
public void mouseReleased(MouseEvent evt) {
draggingAndStartedInside = false;
}

Called Methods

No outgoing method calls

setUp

Class: jfreerails.controller.FlatTrackExplorerTest

Documentation

/**
* Sets up the test environment by initializing a world, adding a test player,
* configuring game rules to no restrictions, generating track rule lists,
* and creating/validating track piece construction moves.
*
* This method initializes a {@link jfreerails.world.top.WorldImpl} instance,
* adds a test player, sets game rules to {@link ITEM.GAME_RULES} with
* {@link GameRules.NO_RESTRICTIONS}, generates track rules via
* {@link MapFixtureFactory.generateTrackRuleList}, and constructs
* multiple {@link ChangeTrackPieceCompositeMove} instances to build track
* pieces. Each move is executed and verified to ensure success.
*
* @param none
* @return void
* @throws none
*/

Source Code

@Override
protected void setUp() {
world = new WorldImpl(20, 20);
world.addPlayer(testPlayer);
world.set(ITEM.GAME_RULES, GameRules.NO_RESTRICTIONS);
MapFixtureFactory.generateTrackRuleList(world);
TrackRule rule = (TrackRule) world.get(SKEY.TRACK_RULES, 0);
Step[] vectors = { Step.WEST, Step.EAST, Step.NORTH_EAST };
ImPoint p = new ImPoint(10, 10);
ImPoint[] points = { p, p, p };
for (int i = 0; i < points.length; i++) {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(points[i], vectors[i], rule, rule,
world, MapFixtureFactory.TEST_PRINCIPAL);
MoveStatus ms = move.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.ok);
}
}

noChange

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void noChange() {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
newOrders = new TrainOrdersModel(oldOrders.getStationID(), null, false,
false);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}

move

Class: jfreerails.move.ChangeItemInListMove

Documentation

No documentation available

Source Code

protected MoveStatus move(FreerailsSerializable to,
FreerailsSerializable from, World w) {
MoveStatus ms = tryMove(to, from, w);
if (ms.ok) {
w.set(principal, listKey, index, to);
}
return ms;
}

refreshTile

Class: jfreerails.client.renderer.MapLayerRenderer

Documentation

No documentation available

Source Code

void refreshTile(int x, int y);

Called Methods

No outgoing method calls

removeConnection

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

private void removeConnection(NameAndPassword p) throws IOException {
String[] before = getPlayerNames();
Connection2Client connection = acceptedConnections.get(p);
/*
* Fix for bug 1047439 Shutting down remote client crashes server We get
* an IllegalStateException if we try to disconnect a connection that is
* not open.
*/
if (connection.isOpen()) {
connection.disconnect();
}
this.currentlyLoggedOn.remove(p);
String[] after = getPlayerNames();
propertyChangeSupport.firePropertyChange("CONNECTED_PLAYERS", before,
after);
}

addStationActionPerformed

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

No documentation available

Source Code

private void addStationActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addStationActionPerformed
setVisible(false, false, false, true);
setTrackBuilderMode(BUILD_STATION);
}// GEN-LAST:event_addStationActionPerformed

generateNewSchedule

Class: jfreerails.client.view.SelectStationJPanel

Documentation

No documentation available

Source Code

public MutableSchedule generateNewSchedule() {
TrainOrdersModel oldOrders, newOrders;
oldOrders = schedule.getOrder(selectedOrderNumber);
newOrders = new TrainOrdersModel(selectedStationID, oldOrders
.getConsist(), oldOrders.getWaitUntilFull(), oldOrders
.isAutoConsist());
schedule.setOrder(selectedOrderNumber, newOrders);
return schedule;
}

setMapView

Class: jfreerails.client.view.MapViewJComponent

Documentation

No documentation available

Source Code

void setMapView(MapRenderer mapView) {
this.mapView = mapView;
}

Called Methods

No outgoing method calls

testMustConnect2ExistingTrack

Class: jfreerails.move.ChangeTrackPieceCompositeMoveTest

Documentation

/**
* All track except the first piece built should be connected to existing
* track.
*/

Source Code

/**
* All track except the first piece built should be connected to existing
* track.
*/
public void testMustConnect2ExistingTrack() {
TrackRule trackRule = (TrackRule) world.get(SKEY.TRACK_RULES, 0);
int numberOfTransactions = world
.getNumberOfTransactions(MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(0, numberOfTransactions);
boolean hasTrackBeenBuilt = ChangeTrackPieceCompositeMove
.hasAnyTrackBeenBuilt(world, MapFixtureFactory.TEST_PRINCIPAL);
assertFalse("No track has been built yet.", hasTrackBeenBuilt);
assertBuildTrackSucceeds(new ImPoint(0, 5), east, trackRule);
// Building the track should have added a transaction.
numberOfTransactions = world
.getNumberOfTransactions(MapFixtureFactory.TEST_PRINCIPAL);
assertTrue(0 < numberOfTransactions);
hasTrackBeenBuilt = ChangeTrackPieceCompositeMove.hasAnyTrackBeenBuilt(
world, MapFixtureFactory.TEST_PRINCIPAL);
assertTrue("One track piece has been built.", hasTrackBeenBuilt);
assertBuildTrackSucceeds(new ImPoint(1, 5), east, trackRule);
assertBuildTrackFails(new ImPoint(4, 8), east, trackRule);
}

getPasswords

Class: jfreerails.network.specifics.ServerGameModel

Documentation

No documentation available

Source Code

String[] getPasswords();

Called Methods

No outgoing method calls

contains

Class: jfreerails.controller.OpenList

Documentation

No documentation available

Source Code

boolean contains(int node) {
boolean containsKey = map.containsKey(node);
return containsKey;
}

Called Methods

No outgoing method calls

showHow2Play

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showHow2Play() {
showContent(this.how2play);
}

toString

Class: jfreerails.move.MoveStatus

Documentation

No documentation available

Source Code

@Override
public String toString() {
return message;
}

Called Methods

No outgoing method calls

calNumOfEachTrackType

Class: jfreerails.server.TrackMaintenanceMoveGeneratorTest

Documentation

No documentation available

Source Code

private int[] calNumOfEachTrackType() {
int[] actual;
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
w, MapFixtureFactory.TEST_PRINCIPAL);
actual = new int[3];
aggregator.setType(0);
actual[0] = aggregator.calculateQuantity();
aggregator.setType(1);
actual[1] = aggregator.calculateQuantity();
aggregator.setType(2);
actual[2] = aggregator.calculateQuantity();
return actual;
}

contains

Class: jfreerails.world.common.FlatTrackTemplate

Documentation

/**
* @param ftt
* the FlatTrackTemplate which may be a subset of this
* FlatTrackTemplate.
* @return true if the vectors represented by this FlatTrackTemplate are a
* superset of the vectors of the specified FlatTrackTemplate
*/

Source Code

/**
* @param ftt
* the FlatTrackTemplate which may be a subset of this
* FlatTrackTemplate.
* @return true if the vectors represented by this FlatTrackTemplate are a
* superset of the vectors of the specified FlatTrackTemplate
*/
boolean contains(FlatTrackTemplate ftt);

Called Methods

No outgoing method calls

WagonCellRenderer

Class: jfreerails.client.view.WagonCellRenderer

Documentation

No documentation available

Source Code

public WagonCellRenderer(World2ListModelAdapter w2lma, RenderersRoot s) {
rr = s;
labels = new Component[w2lma.getSize()];
for (int i = 0; i < w2lma.getSize(); i++) {
JLabel label = new JLabel();
label.setFont(new java.awt.Font("Dialog", 0, 12));
Image image = rr.getWagonImages(i).getSideOnImage();
int height = image.getHeight(null);
int width = image.getWidth(null);
int scale = height / 10;
ImageIcon icon = new ImageIcon(image.getScaledInstance(width
/ scale, height / scale, Image.SCALE_FAST));
label.setIcon(icon);
labels[i] = label;
}
}

EconomicClimate

Class: jfreerails.world.accounts.EconomicClimate

Documentation

No documentation available

Source Code

private EconomicClimate(int r, String s) {
baseInterestRate = r;
name = s;
}

Called Methods

No outgoing method calls

autoConsist

Class: jfreerails.world.train.Schedule

Documentation

/** Returns the value for the autoconsist flag at the next scheduled stop. */

Source Code

/** Returns the value for the autoconsist flag at the next scheduled stop. */
boolean autoConsist();

Called Methods

No outgoing method calls

FreerailsPathIteratorImpl

Class: jfreerails.world.common.FreerailsPathIteratorImpl

Documentation

/** Creates new FreerailsPathIteratorImpl */

Source Code

/** Creates new FreerailsPathIteratorImpl */
public FreerailsPathIteratorImpl(List<Point> l, boolean f) {
points = l;
forwards = f;
if (forwards) {
this.position = 0;
} else {
this.position = l.size() - 1; // The last element of a list of
// size 7 is at position 6.
}
}

Called Methods

No outgoing method calls

listDiffs

Class: jfreerails.world.top.WorldDiffs

Documentation

/** Used by unit tests. */

Source Code

/** Used by unit tests. */
public int listDiffs() {
return listDiff.size();
}

Called Methods

No outgoing method calls

sizeD3

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

public int sizeD3(int d1, int d2) {
return super.size(d1, d2);
}

handle_Produces

Class: jfreerails.server.parser.CargoAndTerrainHandler

Documentation

/**
* An empty element event handling method.
*
*/

Source Code

/**
* An empty element event handling method.
*
*/
public void handle_Produces(final Attributes meta) throws SAXException;

Called Methods

No outgoing method calls

refreshAll

Class: jfreerails.client.view.MapViewJComponentConcrete

Documentation

No documentation available

Source Code

public void refreshAll() {
this.getMapView().refreshAll();
}

hashCode

Class: jfreerails.world.common.ImInts

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return ints.length;
}

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.top.BuildIndustryJPopupMenu

Documentation

No documentation available

Source Code

public void setup(final ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
this.removeAll();
final NonNullElements it = new NonNullElements(SKEY.TERRAIN_TYPES,
modelRoot.getWorld());
while (it.next()) {
TerrainType type = (TerrainType) it.getElement();
final Money price = type.getBuildCost();
if (null != price) {
JMenuItem item = new JMenuItem(type.getDisplayName() + " "
+ price);
item.addActionListener(new ActionListener() {
private final int terrainType = it.getIndex();
public void actionPerformed(ActionEvent arg0) {
Move m1 = new ChangeTileMove(modelRoot.getWorld(),
cursorLocation, terrainType);
Transaction t = new AddItemTransaction(
Transaction.Category.INDUSTRIES, terrainType,
1, price.changeSign());
Move m2 = new AddTransactionMove(modelRoot
.getPrincipal(), t);
CompositeMove m3 = new CompositeMove(m1, m2);
MoveStatus ms = modelRoot.doMove(m3);
if (!ms.ok) {
modelRoot.setProperty(
ModelRoot.Property.CURSOR_MESSAGE,
ms.message);
}
}
});
add(item);
}
}
}

undoMove

Class: jfreerails.move.WorldDiffMove

Documentation

No documentation available

Source Code

public MoveStatus undoMove(World world, FreerailsPrincipal p) {
MoveStatus ms = tryMapChanges(world, true);
if (!ms.ok)
return ms;
ms = listChanges.undoMove(world, p);
if (ms.isOk()) {
doMove(world, true);
}
return ms;
}

setValue

Class: jfreerails.util.Unknown

Documentation

No documentation available

Source Code

public void setValue(int i) {
}

Called Methods

No outgoing method calls

Step

Class: jfreerails.world.common.Step

Documentation

/**
* Create a new OneTileMoveVector. N.B Private constructor to enforce enum
* property, use getInstance(x,y) instead. Pass values for delta X and Y:
* they must be in the range -1 to 1 and cannot both be equal to 0.
*
* @param x
* Tile coordinate.
* @param y
* Tile coordinate
* @param t
* an integer representing the track template this vector
* corresponds to.
*/

Source Code

/**
* Create a new OneTileMoveVector. N.B Private constructor to enforce enum
* property, use getInstance(x,y) instead. Pass values for delta X and Y:
* they must be in the range -1 to 1 and cannot both be equal to 0.
*
* @param x
* Tile coordinate.
* @param y
* Tile coordinate
* @param t
* an integer representing the track template this vector
* corresponds to.
*/
private Step(int x, int y, int t) {
deltaX = x;
deltaY = y;
flatTrackTemplate = t;
length = (x * y) == 0 ? TILE_DIAMETER : TILE_DIAGONAL;
}

Called Methods

No outgoing method calls

NewsPaperJPanel

Class: jfreerails.client.view.NewsPaperJPanel

Documentation

No documentation available

Source Code

public NewsPaperJPanel() {
initComponents();
Image tempImage = (new javax.swing.ImageIcon(getClass().getResource(
"/jfreerails/data/newspaper.png"))).getImage();
pieceOfNewspaper = defaultConfiguration.createCompatibleImage(tempImage
.getWidth(null), tempImage.getHeight(null),
Transparency.BITMASK);
Graphics g = pieceOfNewspaper.getGraphics();
g.drawImage(tempImage, 0, 0, null);
this.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mousePressed(java.awt.event.MouseEvent evt) {
callBack.actionPerformed(new ActionEvent(this, 0, null));
}
});
}

generateFileNameNumber

Class: jfreerails.client.renderer.StandardTileRenderer

Documentation

No documentation available

Source Code

@Override
protected String generateFileNameNumber(int i) {
throw new UnsupportedOperationException();
}

Called Methods

No outgoing method calls

paintRect

Class: jfreerails.client.view.DetailMapRenderer

Documentation

No documentation available

Source Code

public void paintRect(Graphics g, Rectangle visibleRect) {
background.paintRect(g, visibleRect);
trainsview.paint((Graphics2D) g);
stationRadius.paint((Graphics2D) g);
stationBoxes.paint((Graphics2D) g);
buildTrackRenderer.paint((Graphics2D) g);
}

move

Class: jfreerails.world.common.Step

Documentation

No documentation available

Source Code

public static ImPoint move(ImPoint p, Step... path) {
int x = p.x;
int y = p.y;
for (Step v : path) {
x += v.deltaX;
y += v.deltaY;
}
return new ImPoint(x, y);
}

Called Methods

No outgoing method calls

get

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public FreerailsSerializable get(FreerailsPrincipal p, KEY key, int index) {
int playerIndex = p.getWorldIndex();
return lists.get(playerIndex, key.getKeyID(), index);
}

precommitMoves

Class: jfreerails.network.specifics.MovePrecommitter

Documentation

No documentation available

Source Code

void precommitMoves() {
blocked = false;
while (uncomitted.size() > 0 && !blocked) {
Object first = uncomitted.getFirst();
if (first instanceof Move) {
Move m = (Move) first;
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
if (ms.ok) {
uncomitted.removeFirst();
precomitted.addLast(m);
} else {
blocked = true;
}
} else if (first instanceof PreMove) {
PreMove pm = (PreMove) first;
Move m = pm.generateMove(w);
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
if (ms.ok) {
uncomitted.removeFirst();
PreMoveAndMove pmam = new PreMoveAndMove(pm, m);
precomitted.addLast(pmam);
} else {
blocked = true;
}
}
}
}

main

Class: experimental.AnimationExpt

Documentation

No documentation available

Source Code

public static void main(String[] args) {
System.setProperty("SHOWFPS", "true");
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.getContentPane().add(new AnimationExpt());
ScreenHandler screenHandler = new ScreenHandler(f,
ScreenHandler.WINDOWED_MODE);
screenHandler.apply();
GameLoop gameLoop = new GameLoop(screenHandler);
Thread t = new Thread(gameLoop);
t.start();
}

getFinalPosition

Class: jfreerails.world.train.TrainMotion

Documentation

No documentation available

Source Code

public PositionOnTrack getFinalPosition() {
return path.getFinalPosition();
}

getDemand

Class: jfreerails.world.station.StationModel

Documentation

No documentation available

Source Code

public Demand4Cargo getDemand() {
return demand;
}

Called Methods

No outgoing method calls

testAdd

Class: jfreerails.util.ListXDTest

Documentation

No documentation available

Source Code

public void testAdd(){
//Test initial size.
assertEquals(0, list1d.size());
assertEquals(5, list2d.sizeD1());
assertEquals(0, list2d.sizeD2(0));
//Add an object
Integer i = new Integer(4);
assertEquals(0, list1d.add(i));
assertEquals(0, list2d.addD2(2, i));
assertEquals(1, list1d.size());
assertEquals(5, list2d.sizeD1());
assertEquals(1, list2d.sizeD2(2));
assertEquals(0, list2d.sizeD2(0));
}

moveCursorJump

Class: jfreerails.client.top.UserInputOnMapController

Documentation

No documentation available

Source Code

private void moveCursorJump(ImPoint tryThisPoint) {
setCursorMessage("");
if (legalRectangleContains(tryThisPoint)) {
setCursorPosition(tryThisPoint);
cursorJumped(tryThisPoint);
} else {
this.setCursorMessage("Illegal cursor position!");
}
}

testPopulateTokens

Class: jfreerails.client.view.HtmlJPanelTest

Documentation

No documentation available

Source Code

public void testPopulateTokens() {
String template = "test";
HashMap<String, String> context = new HashMap<String, String>();
String output = HtmlJPanel.populateTokens(template, context);
assertEquals(template, output);
template = "Hello $name$, $question$";
context.put("name", "Luke");
context.put("question", "how are you?");
String expectedOutput = "Hello Luke, how are you?";
output = HtmlJPanel.populateTokens(template, context);
assertEquals(expectedOutput, output);
Object objectContext = new Object() {
@SuppressWarnings("unused")
public String name = "Luke";
@SuppressWarnings("unused")
public String question = "how are you?";
};
output = HtmlJPanel.populateTokens(template, objectContext);
assertEquals(expectedOutput, output);
}

getConverted

Class: jfreerails.world.station.StationModel

Documentation

No documentation available

Source Code

public ConvertedAtStation getConverted() {
return converted;
}

Called Methods

No outgoing method calls

getID

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public int getID(FreerailsPrincipal p) {
return p.getWorldIndex();
}

undoMove

Class: jfreerails.move.AddActiveEntityMove

Documentation

No documentation available

Source Code

public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.ok)
w.removeLastActiveEntity(principal);
return ms;
}

getStationToGoto

Class: jfreerails.world.train.MutableSchedule

Documentation

/**
* Returns the station number of the next station the train is scheduled to
* stop at.
*/

Source Code

/**
* Returns the station number of the next station the train is scheduled to
* stop at.
*/
public int getStationToGoto() {
return orders.get(nextScheduledOrder).getStationID();
}

removeLast

Class: jfreerails.util.List1D

Documentation

No documentation available

Source Code

T removeLast();

Called Methods

No outgoing method calls

CityModel

Class: jfreerails.world.terrain.CityModel

Documentation

No documentation available

Source Code

public CityModel(String s, int xx, int yy) {
name = s;
x = xx;
y = yy;
}

Called Methods

No outgoing method calls

InetConnection

Class: jfreerails.network.InetConnection

Documentation

No documentation available

Source Code

InetConnection(Socket acceptedConnection) throws IOException {
socket = acceptedConnection;
}

Called Methods

No outgoing method calls

get

Class: jfreerails.world.common.ImInts

Documentation

No documentation available

Source Code

public int get(int i) {
return ints[i];
}

Called Methods

No outgoing method calls

waitForObjectFromServer

Class: jfreerails.network.LocalConnection

Documentation

No documentation available

Source Code

public FreerailsSerializable waitForObjectFromServer() throws IOException,
InterruptedException {
if (status.isOpen()) {
synchronized (fromServer) {
if (fromServer.size() == 0) {
fromServer.wait();
}
return fromServer.getFirst();
}
}
throw new IOException();
}

paintComponent

Class: jfreerails.client.view.SelectStationJPanel

Documentation

No documentation available

Source Code

@Override
protected void paintComponent(Graphics g) {
if (needsUpdating) {
this.setZoom();
}
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
NonNullElements it = new NonNullElements(KEY.STATIONS, world,
this.principal);
// Draw track
g2.setColor(Color.BLACK);
for (int x = Math.max(0, visibleMapTiles.x); x < Math.min(
visibleMapTiles.width + visibleMapTiles.x, world.getMapWidth()); x++) {
for (int y = Math.max(0, visibleMapTiles.y); y < Math.min(
visibleMapTiles.height + visibleMapTiles.y, world
.getMapHeight()); y++) {
FreerailsTile tt = (FreerailsTile) world.getTile(x, y);
if (!tt.getTrackPiece().equals(NullTrackPiece.getInstance())) {
double xDouble = x - visibleMapTiles.x;
xDouble = xDouble * scale;
double yDouble = y - visibleMapTiles.y;
yDouble = yDouble * scale;
g.drawRect((int) xDouble, (int) yDouble, 1, 1);
}
}
}
// Draw stations
while (it.next()) {
/*
* (1) The selected station is drawn green. (2) Non-selected
* stations which are on the schedule are drawn blue. (3) Other
* stations are drawn white. (4) If, for instance, station X is the
* first stop on the schedule, "1" is drawn above the station. (5)
* If, for instance, station X is the first and third stop on the
* schedule, "1, 3" is drawn above the station. (6) The stop numbers
* drawn above the stations are drawn using the same colour as used
* to draw the station.
*/
StationModel station = (StationModel) it.getElement();
double x = station.x - visibleMapTiles.x;
x = x * scale;
double y = station.y - visibleMapTiles.y;
y = y * scale;
int xInt = (int) x;
int yInt = (int) y;
String stopNumbersString = "";
boolean stationIsOnSchedule = false;
for (int orderNumber = 0; orderNumber < schedule.getNumOrders(); orderNumber++) {
int stationID = orderNumber == this.selectedOrderNumber ? this.selectedStationID
: schedule.getOrder(orderNumber).getStationID();
if (it.getIndex() == stationID) {
if (stationIsOnSchedule) {
stopNumbersString = stopNumbersString + ", "
+ String.valueOf(orderNumber + 1);
} else {
stopNumbersString = String.valueOf(orderNumber + 1);
}
stationIsOnSchedule = true;
}
}
if (stationIsOnSchedule) {
if (it.getIndex() == selectedStationID) {
g2.setColor(Color.GREEN);
} else {
g2.setColor(Color.BLUE);
}
g2.drawString(stopNumbersString, xInt, yInt - 4);
} else {
g2.setColor(Color.WHITE);
}
g2.fillRect(xInt, yInt, 10, 10);
}
}

main

Class: jfreerails.server.parser.RunTypesParser

Documentation

No documentation available

Source Code

public static void main(String[] args) {
try {
java.net.URL url = RunTypesParser.class
.getResource("/jfreerails/data/cargo_and_terrain.xml");
CargoAndTerrainParser.parse(url, new CargoAndTerrainHandlerImpl(
new WorldImpl()));
logger.info("It worked");
} catch (Exception e) {
e.printStackTrace();
}
}

paintTrackConf

Class: experimental.TrackRenderer

Documentation

No documentation available

Source Code

void paintTrackConf(Graphics2D g2, TrackConfiguration conf) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Draw title
// String title = BinaryNumberFormatter.formatWithLowBitOnLeft(conf
// .get9bitTemplate(), 9);
// g.setColor(Color.BLACK);
// g.setFont(font);
//
// g.drawString(title, 10, 10);
Step[] directions = Step.getList();
List<CubicCurve2D.Double> sections = new ArrayList<CubicCurve2D.Double>();
int matches = 0;
for (int i = 0; i < directions.length - 2; i++) {
if (conf.contains(directions[i])) {
// System.out.println("\n"+directions[i]+" to ..");
int maxJ = Math.min(i + 7, directions.length);
for (int j = i + 2; j < maxJ; j++) {
// System.out.println(directions[j]);
if (conf.contains(directions[j])) {
Double toCurve = toCurve(directions[i], directions[j]);
if (doubleTrack) {
sections.add(createAdjacentCurve(toCurve,
doubleTrackGap, doubleTrackGap));
sections.add(createAdjacentCurve(toCurve,
-doubleTrackGap, -doubleTrackGap));
} else {
sections.add(toCurve);
}
matches++;
}
}
}
}
if (matches == 0) {
for (int i = 0; i < directions.length; i++) {
if (conf.contains(directions[i])) {
Double toCurve = toCurve(directions[i]);
if (doubleTrack) {
sections.add(createAdjacentCurve(toCurve,
doubleTrackGap, doubleTrackGap));
sections.add(createAdjacentCurve(toCurve,
-doubleTrackGap, -doubleTrackGap));
} else {
sections.add(toCurve);
}
}
}
}
paintTrack(g2, sections);
}

testBuildTrack

Class: jfreerails.move.ChangeTrackPieceCompositeMoveTest

Documentation

No documentation available

Source Code

public void testBuildTrack() {
ImPoint pointA = new ImPoint(0, 0);
ImPoint pointB = new ImPoint(1, 1);
ImPoint pointC = new ImPoint(1, 0);
TrackRule trackRule = (TrackRule) getWorld().get(SKEY.TRACK_RULES, 0);
// First track piece built
assertBuildTrackSucceeds(pointA, southeast, trackRule);
// Track connected from one existing track piece
assertBuildTrackSucceeds(pointB, northeast, trackRule);
// Track connected to one existing track piece
// This is not going through for some reason, not sure why.
// assertBuildTrackSucceeds(pointC, west, trackRule);
// Track connecting two existing track pieces.
assertBuildTrackSucceeds(pointA, east, trackRule);
// Track off map.. should fail.
assertBuildTrackFails(pointA, northeast, trackRule);
// Track already there.
assertBuildTrackFails(pointA, southeast, trackRule);
// Illegal config. connecting from one existing track piece
assertBuildTrackFails(pointA, south, trackRule);
// Illegal config. connecting to one existing track piece
assertBuildTrackFails(new ImPoint(0, 1), northeast, trackRule);
// Illegal config. connecting between two existing track pieces
assertBuildTrackFails(pointC, south, trackRule);
// Not allowed on this terrain type, from existing track.
assertBuildTrackFails(new ImPoint(2, 0), northeast,
(TrackRule) getWorld().get(SKEY.TRACK_RULES, 1));
}

testConstrainedMove

Class: jfreerails.move.AddTransactionMoveTest

Documentation

No documentation available

Source Code

public void testConstrainedMove() {
Money currentBalance = getWorld().getCurrentBalance(
MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(new Money(0), currentBalance);
Transaction t = new Bill(new Money(100),
Transaction.Category.MISC_INCOME);
Move m = new AddTransactionMove(MapFixtureFactory.TEST_PRINCIPAL, t,
true);
// This move should fail since there is no money in the account and
// it is constrained is set to true.
assertTryMoveFails(m);
}

readResolve

Class: jfreerails.world.common.Step

Documentation

No documentation available

Source Code

private Object readResolve() throws ObjectStreamException {
return Step.getInstance(this.deltaX, this.deltaY);
}

removeLastD2

Class: jfreerails.util.List2DDiff

Documentation

No documentation available

Source Code

public T removeLastD2(int d1) {
return super.removeLast(d1);
}

EngineType

Class: jfreerails.world.train.EngineType

Documentation

No documentation available

Source Code

public EngineType(String name, int power, Money m, int speed) {
engineTypeName = name;
powerAtDrawbar = power;
price = m;
maxSpeed = speed;
maintenance = new Money(0);
}

Called Methods

No outgoing method calls

execute

Class: jfreerails.network.specifics.SaveGameMessage2Server

Documentation

No documentation available

Source Code

public MessageStatus execute(ServerControlInterface server) {
try {
server.savegame(filename);
return new MessageStatus(id, true);
} catch (Exception e) {
return new MessageStatus(id, false, e.getMessage());
}
}

PreMoveStatus

Class: jfreerails.controller.PreMoveStatus

Documentation

No documentation available

Source Code

private PreMoveStatus(MoveStatus ms) {
this.ms = ms;
}

Called Methods

No outgoing method calls

dumpImages

Class: experimental.LineDrawTrackPieceView

Documentation

No documentation available

Source Code

public void dumpImages(ImageManager imageManager) {
// TODO Auto-generated method stub
}

Called Methods

No outgoing method calls

formKeyPressed

Class: jfreerails.client.view.NewsPaperJPanel

Documentation

No documentation available

Source Code

// GEN-END:initComponents
private void formKeyPressed(java.awt.event.KeyEvent evt) { // GEN-FIRST:event_formKeyPressed
// Add your handling code here:
this.setVerifyInputWhenFocusTarget(false);
}

Called Methods

No outgoing method calls

testFindpath

Class: jfreerails.controller.SimpleAStarPathFinderTest

Documentation

No documentation available

Source Code

public void testFindpath() {
setUp();
int i = pathFinder.findstep(0, new int[] { 1 }, map);
assertEquals(1, i);
i = pathFinder.findstep(0, new int[] { 5 }, map);
assertEquals(1, i);
i = pathFinder.findstep(0, new int[] { 4 }, map);
assertEquals(1, i);
i = pathFinder.findstep(5, new int[] { 7 }, map);
assertEquals(6, i);
i = pathFinder.findstep(4, new int[] { 1 }, map);
assertEquals(2, i);
i = pathFinder.findstep(5, new int[] { 0, 7 }, map);
assertEquals(6, i);
i = pathFinder.findstep(5, new int[] { 4 }, map);
assertEquals(2, i);
i = pathFinder.findstep(4, new int[] { 4 }, map);
assertEquals(IncrementalPathFinder.PATH_NOT_FOUND, i);
i = pathFinder.findstep(2, new int[] { 1 }, map);
assertEquals(1, i);
}

tryMove

Class: jfreerails.move.ChangeTrackPieceMove

Documentation

No documentation available

Source Code

private MoveStatus tryMove(World w, TrackPiece oldTrackPiece,
TrackPiece newTrackPiece) {
// Check that location is on the map.
if (!w.boundsContain(location.x, location.y)) {
return MoveStatus
.moveFailed("Tried to build track outside the map.");
}
// Check that we are not changing another players track if this is not
// allowed.
if (!canConnect2OtherRRsTrack(w)) {
// If either the new or old track piece is null, we are ok.
int oldRuleNumber = oldTrackPiece.getTrackTypeID();
int newRuleNumber = newTrackPiece.getTrackTypeID();
if (NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER != oldRuleNumber
&& NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER != newRuleNumber) {
int oldOwner = oldTrackPiece.getOwnerID();
int newOwner = newTrackPiece.getOwnerID();
if (oldOwner != newOwner) {
return MoveStatus
.moveFailed("Not allowed to connect to other RR");
}
}
}
// Check that the current track piece at this.location is
// the same as this.oldTrackPiece.
TrackPiece currentTrackPieceAtLocation = ((FreerailsTile) w.getTile(
location.x, location.y)).getTrackPiece();
TrackRule expectedTrackRule = oldTrackPiece.getTrackRule();
TrackRule actualTrackRule = currentTrackPieceAtLocation.getTrackRule();
if (!expectedTrackRule.equals(actualTrackRule)) {
return MoveStatus.moveFailed("Expected '"
+ expectedTrackRule.getTypeName() + "' but found '"
+ actualTrackRule.getTypeName() + "' at " + location.x
+ " ," + location.y);
}
if (currentTrackPieceAtLocation.getTrackConfiguration() != oldTrackPiece
.getTrackConfiguration()) {
return MoveStatus
.moveFailed("Unexpected track piece found at location: "
+ location.x + " ," + location.y);
}
// Check that oldTrackPiece is not the same as newTrackPiece
if ((oldTrackPiece.getTrackConfiguration() == newTrackPiece
.getTrackConfiguration())
&& (oldTrackPiece.getTrackRule() == newTrackPiece
.getTrackRule())) {
return MoveStatus.moveFailed("Already track here!");
}
// Check for illegal track configurations.
if (!(oldTrackPiece.getTrackRule().trackPieceIsLegal(
oldTrackPiece.getTrackConfiguration()) && newTrackPiece
.getTrackRule().trackPieceIsLegal(
newTrackPiece.getTrackConfiguration()))) {
return MoveStatus.moveFailed("Illegal track configuration.");
}
// Check for diagonal conflicts.
if (!(noDiagonalTrackConflicts(location, oldTrackPiece
.getTrackGraphicID(), w) && noDiagonalTrackConflicts(location,
newTrackPiece.getTrackGraphicID(), w))) {
return MoveStatus
.moveFailed("Illegal track configuration - diagonal conflict");
}
int terrainType = ((FreerailsTile) w.getTile(location.x, location.y))
.getTerrainTypeID();
TerrainType tt = (TerrainType) w.get(SKEY.TERRAIN_TYPES, terrainType);
if (!newTrackPiece.getTrackRule().canBuildOnThisTerrainType(
tt.getCategory())) {
String thisTrackType = newTrackPiece.getTrackRule().getTypeName();
String terrainCategory = tt.getCategory().toString().toLowerCase();
return MoveStatus.moveFailed("Can't build " + thisTrackType
+ " on " + terrainCategory);
}
// Check 4 overlapping stations.
if (newTrackPiece.getTrackRule().isStation()) {
MoveStatus ms = ChangeTrackPieceMove.check4overlap(w, location,
newTrackPiece);
if (!ms.ok)
return ms;
}
return MoveStatus.MOVE_OK;
}

initComponents

Class: jfreerails.client.view.HtmlJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jScrollPane1 = new javax.swing.JScrollPane();
htmlJLabel = new javax.swing.JLabel();
done = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
setMinimumSize(new java.awt.Dimension(400, 300));
jScrollPane1
.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
htmlJLabel.setFont(new java.awt.Font("Dialog", 0, 12));
htmlJLabel.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
jScrollPane1.setViewportView(htmlJLabel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(jScrollPane1, gridBagConstraints);
done.setText("Close");
done.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
doneActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(done, gridBagConstraints);
}// GEN-END:initComponents

setBuildTrackStrategy

Class: jfreerails.controller.BuildTrackExplorer

Documentation

No documentation available

Source Code

public void setBuildTrackStrategy(BuildTrackStrategy trackStrategy) {
if (null == trackStrategy)
throw new NullPointerException();
buildTrackStrategy = trackStrategy;
}

Called Methods

No outgoing method calls

stop

Class: jfreerails.network.InetConnectionAccepter

Documentation

No documentation available

Source Code

public synchronized void stop() throws IOException {
this.keepRunning.close();
serverSocket.close();
// Commented out since it causes exceptions to be thrown, fixes bug
// 979831
// gameServer.stop();
}

getList

Class: jfreerails.world.common.Step

Documentation

/**
* @return a copy of the list of 8 OneTileMoveVectors going clockwise from
* North.
*/

Source Code

/**
* @return a copy of the list of 8 OneTileMoveVectors going clockwise from
* North.
*/
public static Step[] getList() {
return list.clone(); // defensive copy.
}

Called Methods

  • _Dummy_.__Array__.clone (external)

removePropertyChangeListener

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public void removePropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.removePropertyChangeListener(l);
}

Called Methods

No outgoing method calls

cursorJumped

Class: jfreerails.client.top.UserInputOnMapController

Documentation

No documentation available

Source Code

private void cursorJumped(ImPoint to) {
// if (trackBuilder.getTrackBuilderMode() ==
// TrackMoveProducer.UPGRADE_TRACK) {
// MoveStatus ms = trackBuilder.upgradeTrack(to);
//
// if (ms.ok) {
// setCursorMessage("");
// playAppropriateSound();
// } else {
// setCursorMessage(ms.message);
// }
// }
}

Called Methods

No outgoing method calls

getTrain

Class: jfreerails.controller.TrainAccessor

Documentation

No documentation available

Source Code

public TrainModel getTrain() {
return (TrainModel) w.get(p, KEY.TRAINS, id);
}

createCashJLabel

Class: jfreerails.client.top.GUIComponentFactory

Documentation

No documentation available

Source Code

JLabel createCashJLabel();

Called Methods

No outgoing method calls

tryDoMove

Class: jfreerails.move.AddItemToListMove

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.size(this.principal, listKey) != index) {
return MoveStatus.moveFailed("Expected size of "
+ listKey.toString() + " list is " + index
+ " but actual size is " + w.size(this.principal, listKey));
}
return MoveStatus.MOVE_OK;
}

paintComponent

Class: jfreerails.client.view.IncomeStatementHtmlJPanel

Documentation

No documentation available

Source Code

@Override
protected void paintComponent(Graphics g) {
/* Check to see if the text needs updating before painting. */
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
int currentNumberOfTransactions = world
.getNumberOfTransactions(playerPrincipal);
if (currentNumberOfTransactions != lastNumTransactions) {
updateHtml();
}
super.paintComponent(g);
}

checkT

Class: jfreerails.world.train.TrainMotion

Documentation

No documentation available

Source Code

void checkT(double t) {
if (t < 0d || t > duration)
throw new IllegalArgumentException("t=" + t + ", but duration="
+ duration);
}

Called Methods

No outgoing method calls

addCompleteMoveReceiver

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public void addCompleteMoveReceiver(MoveReceiver l) {
this.moveFork.addCompleteMoveReceiver(l);
}

setPosition

Class: jfreerails.controller.BuildTrackExplorer

Documentation

No documentation available

Source Code

public void setPosition(int vertex) {
currentPosition.setValuesFromInt(vertex);
directionInt = 0;
}

PlannedTrain

Class: jfreerails.world.station.PlannedTrain

Documentation

No documentation available

Source Code

public PlannedTrain(int e, int[] wagons) {
engineType = e;
wagonTypes = new ImInts(wagons);
}

Called Methods

No outgoing method calls

setFacing

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

public void setFacing(Step v) {
this.cameFrom = v.getOpposite();
}

trainArrives

Class: jfreerails.client.top.UserMessageGenerator

Documentation

/** Generates a message giving details of any cargo delivered and plays
* a cash register sound to indicate that revenue is coming in.
*/

Source Code

/** Generates a message giving details of any cargo delivered and plays
* a cash register sound to indicate that revenue is coming in.
*/
private void trainArrives(WorldDiffMove wdm) {
ArrayList<DeliverCargoReceipt> cargoDelivered = new ArrayList<DeliverCargoReceipt>();
CompositeMove listChanges = wdm.getListChanges();
for (int i = 0; i < listChanges.size(); i++) {
Move m = listChanges.getMoves().get(i);
if (m instanceof AddTransactionMove) {
AddTransactionMove atm = (AddTransactionMove) m;
if(!atm.getPrincipal().equals(modelRoot.getPrincipal())){
//We don't want to know about other players' income!
return;
}
Transaction t = atm.getTransaction();
if (t instanceof DeliverCargoReceipt) {
DeliverCargoReceipt receipt = (DeliverCargoReceipt) t;
cargoDelivered.add(receipt);
}
}
}
if (cargoDelivered.size() > 0) {
ReadOnlyWorld world = modelRoot.getWorld();
StringBuffer message = new StringBuffer();
DeliverCargoReceipt first = cargoDelivered.get(0);
int stationId = first.getStationId();
int trainId = first.getTrainId();
message.append("Train #");
message.append(trainId + 1); // So that the first train
// is #1, not #0.
message.append(" arrives at ");
StationModel station = (StationModel) world.get(modelRoot
.getPrincipal(), KEY.STATIONS, stationId);
message.append(station.getStationName());
message.append("\n");
long revenue = 0;
int[] cargoQuantities = new int[modelRoot.getWorld().size(
SKEY.CARGO_TYPES)];
for (DeliverCargoReceipt receipt : cargoDelivered) {
CargoBatch batch = receipt.getCb();
revenue += receipt.deltaCash().getAmount();
cargoQuantities[batch.getCargoType()] = receipt
.getQuantity();
}
for (int i = 0; i < cargoQuantities.length; i++) {
int j = cargoQuantities[i];
if (j > 0) {
CargoType cargoType = (CargoType) world.get(
SKEY.CARGO_TYPES, i);
message.append(j);
message.append(" ");
message.append(cargoType.getDisplayName());
message.append("\n");
}
}
message.append("Revenue $");
message.append(formatter.format(revenue));
modelRoot.setProperty(Property.QUICK_MESSAGE, message
.toString());
// Play the sound of cash coming in. The greater the
// revenue,
// the more loops of the sample we play.
int loops = (int) revenue / 4000;
try {
soundManager.playSound(
"/jfreerails/client/sounds/cash.wav", loops);
} catch (Exception e) {
e.printStackTrace();
}
}
}

processMove

Class: jfreerails.network.specifics.FreerailsClient

Documentation

/** Sends move to the server. */

Source Code

/** Sends move to the server. */
final public void processMove(Move move) {
committer.toServer(move);
moveFork.processMove(move);
write(move);
}

duration

Class: jfreerails.world.train.CompositeSpeedAgainstTime

Documentation

No documentation available

Source Code

public double duration() {
return finalT;
}

Called Methods

No outgoing method calls

testMove

Class: jfreerails.move.CompositeMoveTest

Documentation

No documentation available

Source Code

@Override
public void testMove() {
Move[] moves = new Move[4];
moves[0] = new AddItemToListMove(KEY.STATIONS, 0, station1,
MapFixtureFactory.TEST_PRINCIPAL);
moves[1] = new AddItemToListMove(KEY.STATIONS, 1, station2,
MapFixtureFactory.TEST_PRINCIPAL);
moves[2] = new AddItemToListMove(KEY.STATIONS, 2, station3,
MapFixtureFactory.TEST_PRINCIPAL);
moves[3] = new AddItemToListMove(KEY.STATIONS, 3, station4,
MapFixtureFactory.TEST_PRINCIPAL);
Move compositeMove = new CompositeMove(moves);
assertSurvivesSerialisation(compositeMove);
assertTryMoveIsOk(compositeMove);
assertEquals("The stations should not have been add yet.", 0,
getWorld().size(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS));
assertDoMoveIsOk(compositeMove);
assertEquals("The stations should have been add now.", 4, getWorld()
.size(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS));
assertTryUndoMoveIsOk(compositeMove);
assertUndoMoveIsOk(compositeMove);
assertOkButNotRepeatable(compositeMove);
}

calStockPrice

Class: jfreerails.controller.StockPriceCalculator

Documentation

No documentation available

Source Code

static Money calStockPrice(long netWorth, long profitLastyear, int publicShares, int otherRRShares){
if((publicShares + otherRRShares) == 0 ) return new Money(Long.MAX_VALUE);
long price = 2 * (5 * profitLastyear + netWorth) /(2 * publicShares + otherRRShares);
return new Money(price);
}

Called Methods

No outgoing method calls

createDisplayMenu

Class: jfreerails.client.top.GUIComponentFactory

Documentation

No documentation available

Source Code

JMenu createDisplayMenu();

Called Methods

No outgoing method calls

DateJLabel

Class: jfreerails.client.view.DateJLabel

Documentation

No documentation available

Source Code

public DateJLabel() {
this.setText(" ");
}

Called Methods

No outgoing method calls

testPlayers

Class: jfreerails.world.top.WorldDiffsTest

Documentation

No documentation available

Source Code

public void testPlayers() {
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(0, worldDiff.listDiffs());
assertEquals(1, worldDiff.getNumberOfPlayers());
Player p = worldDiff.getPlayer(0);
assertEquals(player0, p);
assertTrue(worldDiff.isPlayer(player0.getPrincipal()));
// Test adding a player.
int n = worldDiff.addPlayer(player1);
assertEquals(1, n);
assertEquals(2, worldDiff.getNumberOfPlayers());
p = worldDiff.getPlayer(1);
assertEquals(player1, p);
assertTrue(worldDiff.isPlayer(player1.getPrincipal()));
}

getCopy

Class: jfreerails.server.MapFixtureFactory2

Documentation

/**
* Returns a world object with a map of size 50*50, 4 players, and track,
* terrain and cargo types as specified in the xml files used by the actual
* game.
*/

Source Code

/**
* Returns a world object with a map of size 50*50, 4 players, and track,
* terrain and cargo types as specified in the xml files used by the actual
* game.
*/
synchronized public static World getCopy() {
if (null == w) {
w = generateWorld();
}
return w.defensiveCopy();
}

getPlayerNames

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public String[] getPlayerNames() {
String[] playerNames = new String[players.size()];
for (int i = 0; i < players.size(); i++) {
playerNames[i] = players.get(i).username;
}
return playerNames;
}

Called Methods

No outgoing method calls

tryDoMove

Class: jfreerails.move.ChangeTileMove

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
FreerailsTile actual = (FreerailsTile) w.getTile(x, y);
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES, actual
.getTerrainTypeID());
if (!type.getCategory().equals(TerrainType.Category.Country)) {
return MoveStatus.moveFailed("Can only build on clear terrain.");
}
if (actual.equals(before)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + before + " but found "
+ actual);
}

BrokerJFrame

Class: jfreerails.client.view.BrokerJFrame

Documentation

No documentation available

Source Code

public BrokerJFrame(URL url) {
initComponents();
setHtml(loadText(url));
}

paintComponent

Class: jfreerails.client.view.StationInfoJPanel

Documentation

No documentation available

Source Code

@Override
protected void paintComponent(Graphics g) {
/* We need to update if the cargo bundle has changed. */
FreerailsPrincipal playerPrincipal = this.modelRoot.getPrincipal();
/*
* Avoid a array out of bounds exception when there are no stations and
* the stations tab is visible.
*/
if (w.boundsContain(playerPrincipal, KEY.CARGO_BUNDLES,
cargoBundleIndex)) {
FreerailsSerializable currentCargoBundle = w.get(playerPrincipal,
KEY.CARGO_BUNDLES, this.cargoBundleIndex);
if (lastCargoBundle != currentCargoBundle) {
this.display();
lastCargoBundle = currentCargoBundle;
}
}
super.paintComponent(g);
}

getWorld

Class: jfreerails.network.specifics.FreerailsClient

Documentation

No documentation available

Source Code

final public World getWorld() {
return world;
}

Called Methods

No outgoing method calls

getB

Class: jfreerails.util.Pair

Documentation

No documentation available

Source Code

public B getB() {
return e2;
}

Called Methods

No outgoing method calls

getDisplayName

Class: jfreerails.world.terrain.NullTerrainType

Documentation

No documentation available

Source Code

public String getDisplayName() {
return "";
}

Called Methods

No outgoing method calls

getVertexConnectedByEdge

Class: jfreerails.controller.GraphExplorer

Documentation

/**
* Returns the vertex that is connected to the current vertex by the current
* edge.
*/

Source Code

/**
* Returns the vertex that is connected to the current vertex by the current
* edge.
*/
int getVertexConnectedByEdge();

Called Methods

No outgoing method calls

getListCellRendererComponent

Class: jfreerails.client.view.WagonCellRenderer

Documentation

No documentation available

Source Code

public Component getListCellRendererComponent(JList list, Object value, /*
* value
* to
* display
*/
int index, /* cell index */
boolean isSelected, /* is the cell selected */
boolean cellHasFocus) /* the list and the cell have the focus */{
if (index >= 0 && index < labels.length) {
CargoType cargoType = (CargoType) value;
String text = "<html><body>"
+ (isSelected ? "<strong>" : "")
+ cargoType.getDisplayName()
+ (isSelected ? "</strong>"
: "&nbsp;&nbsp;&nbsp;&nbsp;"/*
* padding to stop
* word wrap due to
* greater width of
* strong font
*/) + "</body></html>";
((JLabel) labels[index]).setText(text);
return labels[index];
}
return null;
}

sum

Class: jfreerails.world.common.ImInts

Documentation

/** Returns the sum of the ints stored in the list.*/

Source Code

/** Returns the sum of the ints stored in the list.*/
public int sum(){
int sum = 0;
for (int i = 0; i < ints.length; i++) {
sum+=ints[i];
}
return sum;
}

Called Methods

No outgoing method calls

uas

Class: jfreerails.world.train.ConstAcc

Documentation

No documentation available

Source Code

public static ConstAcc uas(double u, double a, double s) {
double t = calcT(u, a, s);
return new ConstAcc(a, t, u, s);
}

resetSelectedWagons

Class: jfreerails.client.view.SelectWagonsJPanel

Documentation

No documentation available

Source Code

public void resetSelectedWagons() {
this.wagons.clear();
}

Called Methods

No outgoing method calls

actionPerformed

Class: jfreerails.client.view.SaveGameAction

Documentation

No documentation available

Source Code

public void actionPerformed(ActionEvent e) {
dbc.showSaveGame();
/*
try {
// @SonnyZ
// Show a JOptionPane that takes in a string from a text box
String filename = JOptionPane.showInputDialog(null,
"Saved Game Name:", "Save Game",
JOptionPane.QUESTION_MESSAGE, null, null,
modelRoot.getPrincipal().getName()).toString();
// Save the current game using the string
modelRoot.setProperty(Property.QUICK_MESSAGE, "Saved game "
+ filename);
Message2Server message2 = new SaveGameMessage2Server(1,
filename + ".sav");
modelRoot.sendCommand(message2);
loadGameAction.setEnabled(true);
} catch (Exception except) {
}
*/
}

setup

Class: jfreerails.client.view.LoadGameJPanel

Documentation

No documentation available

Source Code

public void setup(ModelRoot m, RenderersRoot vl, Action closeAction) {
this.close = closeAction;
modelRoot = m;
updateListOfFiles();
}

StationBoxRenderer

Class: jfreerails.client.renderer.StationBoxRenderer

Documentation

No documentation available

Source Code

public StationBoxRenderer(ReadOnlyWorld world, RenderersRoot vl,
ModelRoot modelRoot) {
this.w = world;
this.bgColor = new Color(0, 0, 200, 60);
this.modelRoot = modelRoot;
// How wide will the wagon images be if we scale them so their height is
// WAGON_IMAGE_HEIGHT?
Image wagonImage = vl.getWagonImages(0).getSideOnImage();
wagonImageWidth = wagonImage.getWidth(null) * WAGON_IMAGE_HEIGHT
/ wagonImage.getHeight(null);
int nrOfCargoTypes = w.size(SKEY.CARGO_TYPES);
cargoImages = new Image[nrOfCargoTypes];
for (int i = 0; i < nrOfCargoTypes; i++) {
String wagonFilename = vl.getWagonImages(i).sideOnFileName;
try {
wagonImage = vl.getScaledImage(wagonFilename,
WAGON_IMAGE_HEIGHT);
} catch (IOException e) {
throw new IllegalArgumentException(wagonFilename);
}
cargoImages[i] = wagonImage;
}
}

testGetIntInt

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List2DDiff.get(int, int)'
*/
public void testGetIntInt() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
assertEquals(String.valueOf(1), underlying.get(0, 0));
assertEquals(String.valueOf(1), diffs.get(0, 0));
}

playAppropriateSound

Class: jfreerails.client.top.UserInputOnMapController

Documentation

No documentation available

Source Code

private void playAppropriateSound() {
switch (trackBuilder.getTrackBuilderMode()) {
case BUILD_TRACK:
case UPGRADE_TRACK:
soundManager.playSound(JFREERAILS_CLIENT_SOUNDS_BUILDTRACK_WAV, 0);
break;
case REMOVE_TRACK:
soundManager.playSound("/jfreerails/client/sounds/removetrack.wav",
0);
break;
default:
// do nothing
}
}

FreerailsTile

Class: jfreerails.world.track.FreerailsTile

Documentation

No documentation available

Source Code

private FreerailsTile(int terrainType, TrackPiece trackPiece) {
this.terrainType = terrainType;
this.trackPiece = trackPiece;
}

Called Methods

No outgoing method calls

generateFileNameNumber

Class: jfreerails.client.renderer.AbstractTileRenderer

Documentation

No documentation available

Source Code

protected abstract String generateFileNameNumber(int i);

Called Methods

No outgoing method calls

getNumberOfPlayers

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

No documentation available

Source Code

int getNumberOfPlayers();

Called Methods

No outgoing method calls

isCanConnect2OtherRRTrack

Class: jfreerails.world.top.GameRules

Documentation

No documentation available

Source Code

public synchronized boolean isCanConnect2OtherRRTrack() {
return canConnect2OtherRRTrack;
}

Called Methods

No outgoing method calls

createGameMenu

Class: jfreerails.client.top.GUIComponentFactoryTestImpl

Documentation

No documentation available

Source Code

public JMenu createGameMenu() {
return gameMenu;
}

Called Methods

No outgoing method calls

addActiveEntity

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public int addActiveEntity(FreerailsPrincipal p, Activity element) {
int playerIndex = p.getWorldIndex();
int index = activityLists.addD2(playerIndex);
ActivityAndTime ant = new ActivityAndTime(element, currentTime()
.getTicks());
activityLists.addD3(playerIndex, index, ant);
return index;
}

setStationTabEnabled

Class: jfreerails.client.view.RHSJTabPane

Documentation

No documentation available

Source Code

public void setStationTabEnabled(boolean enabled) {
// this.setEnabledAt(this.stationInfoIndex, enabled);
}

Called Methods

No outgoing method calls

getStationChooseAction

Class: jfreerails.client.view.StationBuildModel

Documentation

No documentation available

Source Code

public Action getStationChooseAction(Integer ruleID) {
return id2Action.get(ruleID);
}

Called Methods

No outgoing method calls

toCurve

Class: experimental.TrackRenderer

Documentation

No documentation available

Source Code

CubicCurve2D.Double toCurve(Step a) {
float halfTile = tileWidth / 2;
Point2D.Double start, end, one;
start = new Point2D.Double();
start.x = tileWidth + (halfTile * a.deltaX);
start.y = tileWidth + (halfTile * a.deltaY);
one = controlPoint(start);
end = new Point2D.Double(tileWidth, tileWidth);
CubicCurve2D.Double returnValue = new CubicCurve2D.Double();
returnValue.setCurve(start, one, one, end);
return returnValue;
}

addD1

Class: jfreerails.util.List2DDiff

Documentation

No documentation available

Source Code

public int addD1() {
return super.addDimension();
}

Receipt

Class: jfreerails.world.accounts.Receipt

Documentation

No documentation available

Source Code

public Receipt(Money m, Category category) {
this.amount = m;
this.category = category;
}

Called Methods

No outgoing method calls

assertSurvivesSerialisation

Class: jfreerails.move.AbstractMoveTestCase

Documentation

/**
* This method asserts that if we serialise then deserialize the specified
* move, the specified move is equal to the deserialized move. The assertion
* depends on the move being serializable and the equals method being
* implemented correctly. Also checks that the hashcode does not change.
*
* @param m
*/

Source Code

/**
* This method asserts that if we serialise then deserialize the specified
* move, the specified move is equal to the deserialized move. The assertion
* depends on the move being serializable and the equals method being
* implemented correctly. Also checks that the hashcode does not change.
*
* @param m
*/
protected void assertSurvivesSerialisation(FreerailsSerializable m) {
assertEquals("Reflexivity violated: the move does not equal itself", m,
m);
try {
Object o = Utils.cloneBySerialisation(m);
assertEquals(m, o);
assertEquals("The hashcodes should be the same!", m.hashCode(), o
.hashCode());
} catch (Exception e) {
e.printStackTrace();
assertTrue(false);
}
}

getScrollableTracksViewportHeight

Class: jfreerails.client.view.MapViewJComponent

Documentation

/**
* Gets the scrollableTracksViewportHeight attribute of the
* MapViewJComponent object.
*
* @return The scrollableTracksViewportHeight value
*/

Source Code

/**
* Gets the scrollableTracksViewportHeight attribute of the
* MapViewJComponent object.
*
* @return The scrollableTracksViewportHeight value
*/
public boolean getScrollableTracksViewportHeight() {
return false;
}

Called Methods

No outgoing method calls

isSuccessful

Class: jfreerails.controller.MessageStatus

Documentation

/** True if the command was successfully executed. */

Source Code

/** True if the command was successfully executed. */
public boolean isSuccessful() {
return successful;
}

Called Methods

No outgoing method calls

addWagons

Class: jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest

Documentation

No documentation available

Source Code

private void addWagons(ImInts wagons) {
TrainModel train = (TrainModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.TRAINS,
0);
TrainModel newTrain = train.getNewInstance(train.getEngineType(),
wagons);
w.set(MapFixtureFactory.TEST_PRINCIPAL, KEY.TRAINS, 0, newTrain);
}

WagonType

Class: jfreerails.world.train.WagonType

Documentation

No documentation available

Source Code

public WagonType(String name, int category) {
typeName = name;
typeCategory = category;
}

Called Methods

No outgoing method calls

selectTileIcon

Class: jfreerails.client.renderer.AbstractTileRenderer

Documentation

No documentation available

Source Code

int selectTileIcon(int x, int y, ReadOnlyWorld w) {
return 0;
}

Called Methods

No outgoing method calls

setPerformActionOnSetSelectedItem

Class: jfreerails.client.common.ActionAdapter

Documentation

No documentation available

Source Code

public void setPerformActionOnSetSelectedItem(
boolean performActionOnSetSelectedItem) {
this.performActionOnSetSelectedItem = performActionOnSetSelectedItem;
}

Called Methods

No outgoing method calls

calTrainRevenue

Class: jfreerails.client.view.IncomeStatementGenerator

Documentation

No documentation available

Source Code

Money calTrainRevenue(int trainId) {
long amount = 0;
for (int i = 0; i < w.getNumberOfTransactions(this.principal); i++) {
Transaction t = w.getTransaction(principal, i);
GameTime time = w.getTransactionTimeStamp(principal, i);
if (t instanceof DeliverCargoReceipt
&& cal.getYear(time.getTicks()) >= this.startyear) {
DeliverCargoReceipt dcr = (DeliverCargoReceipt) t;
if (dcr.getTrainId() == trainId) {
amount += dcr.deltaCash().getAmount();
}
}
}
return new Money(amount);
}

testSizeD2

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List2DDiff.sizeD2(int)'
*/
public void testSizeD2() {
underlying.addD1();
assertEquals(1, diffs.sizeD1());
assertEquals(0, diffs.sizeD2(0));
underlying.addD2(0, String.valueOf(1));
assertEquals(1, diffs.sizeD2(0));
}

buildArray

Class: jfreerails.util.GrowableBase

Documentation

/**
* Constructs and returns a simple array containing the same data as held in
* a portion of this growable array.
*
* @param type
* element type for constructed array
* @param offset
* start offset in array
* @param length
* number of characters to use
* @return array containing a copy of the data
*/

Source Code

/**
* Constructs and returns a simple array containing the same data as held in
* a portion of this growable array.
*
* @param type
* element type for constructed array
* @param offset
* start offset in array
* @param length
* number of characters to use
* @return array containing a copy of the data
*/
protected Object buildArray(Class type, int offset, int length) {
Object copy = Array.newInstance(type, length);
System.arraycopy(getArray(), offset, copy, 0, length);
return copy;
}

getProduction

Class: jfreerails.world.terrain.TileTypeImpl

Documentation

No documentation available

Source Code

public ImList<Production> getProduction() {
return production;
}

Called Methods

No outgoing method calls

getPrincipal

Class: jfreerails.move.ListMove

Documentation

No documentation available

Source Code

FreerailsPrincipal getPrincipal();

Called Methods

No outgoing method calls

getWorld

Class: jfreerails.controller.MoveExecutor

Documentation

No documentation available

Source Code

ReadOnlyWorld getWorld();

Called Methods

No outgoing method calls

getDirectoryContents

Class: jfreerails.util.ClassPath

Documentation

/**
* This method does the real directory recursion, passing along the the
* corresponding package-path to this directory.
*
* @param pathTo
* the preceding path to this directory
* @param dir
* a directory to search for class files
*/

Source Code

/**
* This method does the real directory recursion, passing along the the
* corresponding package-path to this directory.
*
* @param pathTo
* the preceding path to this directory
* @param dir
* a directory to search for class files
*/
protected LinkedList<String> getDirectoryContents(String pathTo, File dir) {
LinkedList<String> result = new LinkedList<String>();
String pathToHere = pathTo + dir.getName() + File.separator;
File files[] = dir.listFiles();
for (int i = 0; i < files.length; ++i) {
File f = files[i];
if (f.isDirectory()) {
result.addAll(getDirectoryContents(pathToHere, f));
} else {
if (f.getName().endsWith(".class")) {
String absFilePath = pathToHere + f.getName();
result.add(getClassNameFrom(absFilePath));
}
}
}
return result;
}

cargoBatchIterator

Class: jfreerails.world.cargo.CargoBundle

Documentation

/**
* Note, calling hasNext() or next() on the returned iterator throws a
* ConcurrentModificationException if this CargoBundle has changed since the
* iterator was acquired.
*/

Source Code

/**
* Note, calling hasNext() or next() on the returned iterator throws a
* ConcurrentModificationException if this CargoBundle has changed since the
* iterator was acquired.
*/
Iterator<CargoBatch> cargoBatchIterator();

Called Methods

No outgoing method calls

getPrincipal

Class: jfreerails.move.AddItemToListMove

Documentation

No documentation available

Source Code

public FreerailsPrincipal getPrincipal() {
return principal;
}

Called Methods

No outgoing method calls

calculateAmountToAdd

Class: jfreerails.server.CargoAtStationsGenerator

Documentation

No documentation available

Source Code

int calculateAmountToAdd(int amountSuppliedPerYear, int month) {
// Note, jan is month 0.
int totalAtMonthEnd = amountSuppliedPerYear * (month + 1) / 12;
int totalAtMonthStart = amountSuppliedPerYear * (month) / 12;
int amount = totalAtMonthEnd - totalAtMonthStart;
return amount;
}

Called Methods

No outgoing method calls

execute

Class: jfreerails.network.specifics.SetPropertyMessage2Client

Documentation

No documentation available

Source Code

public MessageStatus execute(ClientControlInterface client) {
client.setProperty(key, value);
return new MessageStatus(id, true);
}

NewGameMessage2Server

Class: jfreerails.network.specifics.NewGameMessage2Server

Documentation

No documentation available

Source Code

public NewGameMessage2Server(int id, String s) {
this.id = id;
this.mapName = s;
}

Called Methods

No outgoing method calls

getScale

Class: jfreerails.client.renderer.BlankMapRenderer

Documentation

No documentation available

Source Code

public float getScale() {
return scale;
}

Called Methods

No outgoing method calls

flush

Class: jfreerails.network.LocalConnection

Documentation

No documentation available

Source Code

public void flush() {
// No need to do anything.
}

Called Methods

No outgoing method calls

getNextScheduledOrder

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public int getNextScheduledOrder() {
return this.nextScheduledOrder;
}

Called Methods

No outgoing method calls

getEngineType

Class: jfreerails.world.train.TrainModel

Documentation

No documentation available

Source Code

public int getEngineType() {
return engineTypeId;
}

Called Methods

No outgoing method calls

TrainMotion

Class: jfreerails.world.train.TrainMotion

Documentation

/**
* Creates a new TrainMotion instance.
*
* @param path
* the path the train will take.
* @param engineStep
* the position measured in tiles that trains engine is along the
* path
* @param trainLength
* the length of the train, as returned by
* <code>TrainModel.getLength()</code>.
* @throws IllegalArgumentException
* if trainLength is out the range
* <code>trainLength &gt; TrainModel.WAGON_LENGTH || trainLength &lt; TrainModel.MAX_TRAIN_LENGTH</code>
* @throws IllegalArgumentException
* if
* <code>path.getDistance(engineStep) &lt; trainLength</code>.
* @throws IllegalArgumentException
* if
* <code>(path.getLength() - initialPosition) &gt; speeds.getTotalDistance()</code>.
*/

Source Code

/**
* Creates a new TrainMotion instance.
*
* @param path
* the path the train will take.
* @param engineStep
* the position measured in tiles that trains engine is along the
* path
* @param trainLength
* the length of the train, as returned by
* <code>TrainModel.getLength()</code>.
* @throws IllegalArgumentException
* if trainLength is out the range
* <code>trainLength &gt; TrainModel.WAGON_LENGTH || trainLength &lt; TrainModel.MAX_TRAIN_LENGTH</code>
* @throws IllegalArgumentException
* if
* <code>path.getDistance(engineStep) &lt; trainLength</code>.
* @throws IllegalArgumentException
* if
* <code>(path.getLength() - initialPosition) &gt; speeds.getTotalDistance()</code>.
*/
public TrainMotion(PathOnTiles path, int engineStep, int trainLength,
SpeedAgainstTime speeds) {
if (trainLength < TrainModel.WAGON_LENGTH
|| trainLength > TrainModel.MAX_TRAIN_LENGTH)
throw new IllegalArgumentException();
this.path = path;
this.speeds = speeds;
this.trainLength = trainLength;
if(engineStep > path.steps())
throw new ArrayIndexOutOfBoundsException(String.valueOf(engineStep));
initialPosition = path.getDistance(engineStep);
if (initialPosition < trainLength)
throw new IllegalArgumentException(
"The engine's initial position is not far enough along the path for "
+ "the train's initial position to be specified.");
double totalPathDistance = path.getTotalDistance();
distanceEngineWillTravel = totalPathDistance - initialPosition;
if (distanceEngineWillTravel > speeds.getS())
throw new IllegalArgumentException(
"The train's speed is not defined for the whole of the journey.");
if(distanceEngineWillTravel == 0){
duration = 0d;
}else{
double tempDuration = speeds.calcT(distanceEngineWillTravel);
while((speeds.calcS(tempDuration) - distanceEngineWillTravel) > 0){
tempDuration -= Math.ulp(tempDuration);
}
duration = tempDuration;
}
activity = SpeedTimeAndStatus.TrainActivity.READY;
sanityCheck();
}

getListCellRendererComponent

Class: jfreerails.client.view.TrainListCellRenderer

Documentation

No documentation available

Source Code

public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
int trainID = NonNullElements.row2index(w, KEY.TRAINS, principal, index);
display(trainID);
selected = isSelected;
if (selected) {
if (list.isFocusOwner()) {
setBackground(selectedColor);
} else {
setBackground(selectedColorNotFocused);
}
} else {
setBackground(backgroundColor);
}
return this;
}

getThreadName

Class: jfreerails.network.InetConnection2Server

Documentation

No documentation available

Source Code

@Override
String getThreadName() {
return "InetConnection2Server";
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object obj) {
if (!(obj instanceof List3D))
return false;
return Lists.equals(this, (List3D)obj);
}

condition

Class: jfreerails.world.top.TransactionAggregator

Documentation

/** Returns true if we should count the specified transactions. */

Source Code

/** Returns true if we should count the specified transactions. */
abstract protected boolean condition(int transactionID);

Called Methods

No outgoing method calls

tryDoMove

Class: jfreerails.network.specifics.FreerailsClient

Documentation

/** Tests a move before sending it to the server. */

Source Code

/** Tests a move before sending it to the server. */
final public MoveStatus tryDoMove(Move move) {
return move.tryDoMove(world, Player.AUTHORITATIVE);
}

appendBuildProps

Class: jfreerails.controller.ReportBugTextGenerator

Documentation

No documentation available

Source Code

private static void appendBuildProps(StringBuffer sb) {
String version = null;
String builtBy = null;;
try {
Properties props = new Properties();
InputStream in = ReportBugTextGenerator.class
.getResourceAsStream("/build.properties");
props.load(in);
in.close();
version = props.getProperty("freerails.build");
builtBy = props.getProperty("freerails.built.by");
} catch (Exception e) {
// ignore, there's nothing useful we can do.
}
version = null == version ? "not set" : version;
builtBy = null == builtBy ? "not set" : builtBy;
sb.append("\t");
sb.append(System.getProperty("os.name"));
sb.append(" ");
sb.append(System.getProperty("os.version"));
sb.append("\n\t");
sb.append(System.getProperty("java.vm.name"));
sb.append(" ");
sb.append(System.getProperty("java.version"));
sb.append("\n\t");
sb.append("Freerails build ");
sb.append(version);
sb.append(" compiled by ");
sb.append(builtBy);
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.controller.PreMoveStatus

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return ms.hashCode();
}

add

Class: jfreerails.world.top.World

Documentation

No documentation available

Source Code

void add(FreerailsPrincipal principal, int index, Activity element);

Called Methods

No outgoing method calls

MainMapAndOverviewMapMediator

Class: jfreerails.client.view.MainMapAndOverviewMapMediator

Documentation

No documentation available

Source Code

public MainMapAndOverviewMapMediator() {
}

Called Methods

No outgoing method calls

getTrackPieceView

Class: jfreerails.client.renderer.TrackPieceRendererList

Documentation

No documentation available

Source Code

public TrackPieceRenderer getTrackPieceView(int i) {
if (NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER == i) {
return NullTrackPieceRenderer.instance;
}
return trackPieceViewArray[i];
}

Called Methods

No outgoing method calls

ImHashSet

Class: jfreerails.world.common.ImHashSet

Documentation

No documentation available

Source Code

public ImHashSet(HashSet<E> hashSet) {
this.hashSet = new HashSet<E>(hashSet);
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.world.top.SKEY

Documentation

No documentation available

Source Code

@Override
public String toString() {
return Utils.findConstantFieldName(this);
}

hashCode

Class: jfreerails.world.top.ActivityAndTime

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = act.hashCode();
result = 29 * result + (int) startTime;
return result;
}

Called Methods

No outgoing method calls

getTrackConfiguration

Class: jfreerails.world.track.TrackPiece

Documentation

No documentation available

Source Code

TrackConfiguration getTrackConfiguration();

Called Methods

No outgoing method calls

TrainDescriptionJPanel

Class: jfreerails.client.view.TrainDescriptionJPanel

Documentation

No documentation available

Source Code

public TrainDescriptionJPanel() {
initComponents();
}

cargoBatchIterator

Class: jfreerails.world.cargo.ImmutableCargoBundle

Documentation

No documentation available

Source Code

public Iterator<CargoBatch> cargoBatchIterator() {
return new Iterator<CargoBatch>() {
int index = 0;
public boolean hasNext() {
return index < batches.size();
}
public CargoBatch next() {
CargoBatch o = batches.get(index);
index++;
return o;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}

size

Class: jfreerails.move.CompositeMove

Documentation

No documentation available

Source Code

public int size(){
return moves.size();
}

handle_LegalRouteAcrossNode

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* An empty element event handling method.
*/

Source Code

/**
* An empty element event handling method.
*/
void handle_LegalRouteAcrossNode(final Attributes meta) throws SAXException;

Called Methods

No outgoing method calls

saveSession

Class: jfreerails.world.player.Player

Documentation

/**
* TODO save this player's private data so that they can be re-connected to
* the server at a later point in time.
*/

Source Code

/**
* TODO save this player's private data so that they can be re-connected to
* the server at a later point in time.
*/
public void saveSession(ObjectOutputStream out) throws IOException {
// out.writeObject(privateData);
}

Called Methods

No outgoing method calls

read

Class: jfreerails.util.FlowRateInputStream

Documentation

No documentation available

Source Code

@Override
public int read() throws IOException {
int r = super.in.read();
totalByteReceived += r;
return r;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.move.CompositeMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof CompositeMove))
return false;
final CompositeMove compositeMove = (CompositeMove) o;
if (!moves.equals(compositeMove.moves))
return false;
return true;
}

equals

Class: jfreerails.controller.AddStationPreMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof AddStationPreMove))
return false;
final AddStationPreMove addStationPreMove = (AddStationPreMove) o;
if (ruleNumber != addStationPreMove.ruleNumber)
return false;
if (!p.equals(addStationPreMove.p))
return false;
if (!principal.equals(addStationPreMove.principal))
return false;
return true;
}

updateWorld

Class: jfreerails.client.renderer.BuildTrackController

Documentation

/**
* Saves track into real world
*/

Source Code

/**
* Saves track into real world
*/
public ImPoint updateWorld(TrackMoveProducer trackBuilder) {
ImPoint actPoint = getCursorPosition();
if (buildNewTrack) {
if (builtTrack.size() > 0) {
MoveStatus ms = moveCursorMoreTiles(builtTrack, trackBuilder);
/* Note, reset() will have been called if ms.ok == false */
if (ms.ok) {
actPoint = builtTrack.get(builtTrack.size() - 1);
builtTrack = new ArrayList<ImPoint>();
}
}
} else {
trackBuilder.setBuildTrackStrategy(getBts());
MoveStatus ms = trackBuilder.buildTrack(actPoint, path);
//MoveStatus ms = trackBuilder.buildTrack(startPoint, path);
if (ms.ok) {
actPoint = targetPoint;
setCursorMessage("");
if (REMOVE_TRACK == getBuildMode()) {
soundManager.playSound(
"/jfreerails/client/sounds/removetrack.wav", 0);
} else {
soundManager.playSound(
"/jfreerails/client/sounds/buildtrack.wav", 0);
}
} else {
setCursorMessage(ms.message);
reset();
}
}
hide();
return actPoint;
}

testCanGenerateMove

Class: jfreerails.controller.MoveTrainPreMove2ndTest

Documentation

No documentation available

Source Code

public void testCanGenerateMove() {
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
assertTrue(preMove.isUpdateDue(world));
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, principal);
assertTrue(ms.message, ms.ok);
assertFalse(preMove.isUpdateDue(world));
}

refreshAll

Class: jfreerails.client.renderer.MapBackgroundRender

Documentation

No documentation available

Source Code

public void refreshAll() {
// Do nothing
}

Called Methods

No outgoing method calls

newspaperActionPerformed

Class: experimental.DialogueBoxTester

Documentation

No documentation available

Source Code

private void newspaperActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_newspaperActionPerformed
// Add your handling code here:
dialogueBoxController.showBrokerScreen();
//dialogueBoxController.showNewspaper("New headline!");
}// GEN-LAST:event_newspaperActionPerformed

showJavaProperties

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showJavaProperties() {
showContent(javaProperties);
}

getCargoBundleID

Class: jfreerails.world.train.TrainModel

Documentation

No documentation available

Source Code

public int getCargoBundleID() {
return cargoBundleId;
}

Called Methods

No outgoing method calls

addBtoHeadOfA

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

private TrainPositionOnMap addBtoHeadOfA(TrainPositionOnMap b,
TrainPositionOnMap a) {
if (aHeadEqualsBTail(a, b)) {
int newLength = a.getLength() + b.getLength() - 2;
int[] newXpoints = new int[newLength];
int[] newYpoints = new int[newLength];
int aLength = a.getLength();
int bLength = b.getLength();
// First copy the points from B
for (int i = 0; i < bLength - 1; i++) {
newXpoints[i] = b.getX(i);
newYpoints[i] = b.getY(i);
}
// Second copy the points from A.
for (int i = 1; i < aLength; i++) {
newXpoints[i + bLength - 2] = a.getX(i);
newYpoints[i + bLength - 2] = a.getY(i);
}
return new TrainPositionOnMap(newXpoints, newYpoints,
b.acceleration, b.speed, b.activity);
}
throw new IllegalArgumentException("Tried to add " + b.toString()
+ " to the head of " + a.toString());
}

setRemoteServerPanelVisible

Class: jfreerails.launcher.ClientOptionsJPanel

Documentation

No documentation available

Source Code

void setRemoteServerPanelVisible(boolean b) {
this.jPanel4.setVisible(b);
}

Called Methods

No outgoing method calls

getCategory

Class: jfreerails.world.terrain.TileTypeImpl

Documentation

No documentation available

Source Code

public Category getCategory() {
return terrainCategory;
}

Called Methods

No outgoing method calls

initComponents

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
buildModeButtonGroup = new javax.swing.ButtonGroup();
trackButtonGroup = new javax.swing.ButtonGroup();
bridgeButtonGroup = new javax.swing.ButtonGroup();
stationButtonGroup = new javax.swing.ButtonGroup();
tunnelButtonGroup = new javax.swing.ButtonGroup();
buildModeJPanel = new javax.swing.JPanel();
addTrack = new javax.swing.JToggleButton();
upgradeTrack = new javax.swing.JToggleButton();
addStation = new javax.swing.JToggleButton();
bulldoze = new javax.swing.JToggleButton();
viewMode = new javax.swing.JToggleButton();
trackJPanel = new javax.swing.JPanel();
viewMode1 = new javax.swing.JToggleButton();
bridgesJPanel = new javax.swing.JPanel();
viewMode2 = new javax.swing.JToggleButton();
tunnelsJPanel = new javax.swing.JPanel();
viewMode3 = new javax.swing.JToggleButton();
stationsJPanel = new javax.swing.JPanel();
viewMode4 = new javax.swing.JToggleButton();
spacer = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
setFocusable(false);
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
@Override
public void keyTyped(java.awt.event.KeyEvent evt) {
formKeyTyped(evt);
}
});
buildModeJPanel.setLayout(new java.awt.FlowLayout(
java.awt.FlowLayout.LEFT, 4, 2));
buildModeButtonGroup.add(addTrack);
addTrack.setIcon(getIcon("build track"));
addTrack.setSelected(true);
addTrack.setToolTipText("Build Track");
addTrack.setFocusable(false);
addTrack.setPreferredSize(new java.awt.Dimension(36, 36));
addTrack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addTrackActionPerformed(evt);
}
});
buildModeJPanel.add(addTrack);
buildModeButtonGroup.add(upgradeTrack);
upgradeTrack.setIcon(getIcon("upgrade track"));
upgradeTrack.setToolTipText("Upgrade Track");
upgradeTrack.setFocusable(false);
upgradeTrack.setPreferredSize(new java.awt.Dimension(36, 36));
upgradeTrack.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
upgradeTrackActionPerformed(evt);
}
});
buildModeJPanel.add(upgradeTrack);
buildModeButtonGroup.add(addStation);
addStation.setIcon(getIcon("build stations"));
addStation.setToolTipText("Build Station");
addStation.setFocusable(false);
addStation.setPreferredSize(new java.awt.Dimension(36, 36));
addStation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addStationActionPerformed(evt);
}
});
buildModeJPanel.add(addStation);
buildModeButtonGroup.add(bulldoze);
bulldoze.setIcon(getIcon("bulldozer"));
bulldoze.setToolTipText("Remove Track");
bulldoze.setFocusable(false);
bulldoze.setPreferredSize(new java.awt.Dimension(36, 36));
bulldoze.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bulldozeActionPerformed(evt);
}
});
buildModeJPanel.add(bulldoze);
buildModeButtonGroup.add(viewMode);
viewMode.setIcon(getIcon("eye"));
viewMode.setToolTipText("Don't build anything");
viewMode.setFocusable(false);
viewMode.setPreferredSize(new java.awt.Dimension(36, 36));
viewMode.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewModeActionPerformed(evt);
}
});
buildModeJPanel.add(viewMode);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(buildModeJPanel, gridBagConstraints);
trackJPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT,
4, 2));
buildModeButtonGroup.add(viewMode1);
viewMode1.setIcon(getIcon("turn_off"));
viewMode1.setPreferredSize(new java.awt.Dimension(36, 36));
trackJPanel.add(viewMode1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(trackJPanel, gridBagConstraints);
bridgesJPanel.setLayout(new java.awt.FlowLayout(
java.awt.FlowLayout.LEFT, 4, 2));
buildModeButtonGroup.add(viewMode2);
viewMode2.setIcon(getIcon("turn_off"));
viewMode2.setPreferredSize(new java.awt.Dimension(36, 36));
bridgesJPanel.add(viewMode2);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(bridgesJPanel, gridBagConstraints);
tunnelsJPanel.setLayout(new java.awt.FlowLayout(
java.awt.FlowLayout.LEFT, 4, 2));
buildModeButtonGroup.add(viewMode3);
viewMode3.setIcon(getIcon("turn_off"));
viewMode3.setPreferredSize(new java.awt.Dimension(36, 36));
tunnelsJPanel.add(viewMode3);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(tunnelsJPanel, gridBagConstraints);
stationsJPanel.setLayout(new java.awt.FlowLayout(
java.awt.FlowLayout.LEFT, 4, 2));
buildModeButtonGroup.add(viewMode4);
viewMode4.setIcon(getIcon("turn_off"));
viewMode4.setPreferredSize(new java.awt.Dimension(36, 36));
stationsJPanel.add(viewMode4);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
add(stationsJPanel, gridBagConstraints);
spacer.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 0,
0));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 5;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(spacer, gridBagConstraints);
}// GEN-END:initComponents

getKey

Class: jfreerails.move.ChangeItemInListMove

Documentation

No documentation available

Source Code

public KEY getKey() {
return listKey;
}

Called Methods

No outgoing method calls

doMove

Class: jfreerails.move.CompositeMove

Documentation

No documentation available

Source Code

public final MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = compositeTest(w, p);
if (!ms.ok) {
return ms;
}
for (int i = 0; i < moves.size(); i++) {
ms = moves.get(i).doMove(w, p);
if (!ms.ok) {
// Undo any moves we have already done.
undoMoves(w, i - 1, p);
return ms;
}
}
return ms;
}

getAfter

Class: jfreerails.move.AddItemToSharedListMove

Documentation

No documentation available

Source Code

public FreerailsSerializable getAfter() {
return item;
}

Called Methods

No outgoing method calls

TandI

Class: jfreerails.world.train.TandI

Documentation

No documentation available

Source Code

TandI(int i, double t) {
this.i = i;
this.offset = t;
}

Called Methods

No outgoing method calls

mouseDragged

Class: jfreerails.client.top.CursorMouseAdapter

Documentation

No documentation available

Source Code

@Override
public void mouseDragged(MouseEvent evt
) {
BuildMode trackBuilderMode = trackBuilder.getTrackBuilderMode();
/*
* Fix for bug [ 972866 ] Build track by dragging - only when build
* track selected
* Fix for bug [1537413 ] Exception when building station.
*/
boolean trackBuildingOn = (trackBuilderMode == BUILD_TRACK)
|| (trackBuilderMode == REMOVE_TRACK)
|| (trackBuilderMode == UPGRADE_TRACK);
trackBuildingOn = trackBuildingOn
&& (modelRoot.getProperty(ModelRoot.Property.CURSOR_MODE) == ModelRoot.Value.BUILD_TRACK_CURSOR_MODE);
if (SwingUtilities.isLeftMouseButton(evt) && pressedInside
&& trackBuildingOn && !ignoreDragging) {
setIgnoreKeyEvents(true);
int x = evt.getX();
int y = evt.getY();
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
int tileX = x / tileSize.width;
int tileY = y / tileSize.height;
/*
* See the javadoc for JComponent.setAutoscrolls(boolean
* autoscrolls)
*/
assert mapView.getAutoscrolls();
// Scroll view if necessary.
if (!mapView.getVisibleRect().contains(x, y)) {
/*
* Making the rectangle we scroll to 2 tiles wide and
* centered on x, y means that we scroll at least one tile.
* This stops painfully slow scrolling in full screen mode
* when the mouse cannot be dragged far from the viewport
* since it hits the screen edge.
*/
Rectangle r = new Rectangle(x - tileSize.width, y
- tileSize.height, 2 * tileSize.width,
2 * tileSize.height);
mapView.scrollRectToVisible(r);
}
ImPoint to = new ImPoint(
tileX, tileY);
buildTrack.setProposedTrack(to, trackBuilder);
mapView.requestFocus();
}
}

actionPerformed

Class: jfreerails.client.view.Unknown

Documentation

No documentation available

Source Code

public void actionPerformed(ActionEvent arg0) {
if (financialDataGatherer.canIssueBond()) {
Move bondTransaction = new AddTransactionMove(modelRoot
.getPrincipal(),
BondTransaction.issueBond(financialDataGatherer
.nextBondInterestRate()));
modelRoot.doMove(bondTransaction);
}
}

generateMove

Class: jfreerails.server.InterestChargeMoveGenerator

Documentation

No documentation available

Source Code

private static AddTransactionMove generateMove(World w,
FreerailsPrincipal principal) {
long interestDue = 0;
for (int i = 0; i < w.getNumberOfTransactions(principal); i++) {
Transaction t = w.getTransaction(principal, i);
if (t instanceof BondTransaction) {
BondTransaction bt = (BondTransaction) t;
int interestRate = bt.getType();
long bondAmount = BondTransaction.BOND_VALUE_ISSUE.getAmount();
interestDue += (interestRate * bondAmount / 100)
* bt.getQuantity();
}
}
Transaction t = new Bill(new Money(interestDue),
Transaction.Category.INTEREST_CHARGE);
return new AddTransactionMove(principal, t);
}

moveToNextLimit

Class: jfreerails.world.train.PathWalkerImplTest

Documentation

No documentation available

Source Code

private void moveToNextLimit() {
IntLine line = new IntLine();
while (pw.hasNext()) {
pw.nextSegment(line);
}
}

loadStream

Class: jfreerails.client.common.SoundManager

Documentation

No documentation available

Source Code

private ByteArrayInputStream loadStream(InputStream inputstream)
throws IOException {
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
for (int i = inputstream.read(data); i != -1; i = inputstream
.read(data)) {
bytearrayoutputstream.write(data, 0, i);
}
inputstream.close();
bytearrayoutputstream.close();
data = bytearrayoutputstream.toByteArray();
return new ByteArrayInputStream(data);
}

Called Methods

No outgoing method calls

undoMove

Class: jfreerails.move.AddPlayerMove

Documentation

No documentation available

Source Code

public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (!ms.ok)
return ms;
w.removeLastTransaction(player2add.getPrincipal());
w.removeLastTransaction(player2add.getPrincipal());
w.removeLastPlayer();
return ms;
}

isFirstYear

Class: jfreerails.controller.StockPriceCalculator

Documentation

/** Returns true if the current time in the same year as the first transaction for the
* specified player.
*/

Source Code

/** Returns true if the current time in the same year as the first transaction for the
* specified player.
*/
boolean isFirstYear(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
GameTime firstTransactionTime = w.getTransactionTimeStamp(pr, 0);
GameCalendar calendar = (GameCalendar)w.get(ITEM.CALENDAR);
int year = calendar.getYear(firstTransactionTime.getTicks());
GameTime currentTime = w.currentTime();
int currentYear = calendar.getYear(currentTime.getTicks());
return year == currentYear;
}

profitsLastYear

Class: jfreerails.controller.StockPriceCalculator

Documentation

No documentation available

Source Code

long profitsLastYear(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
GameCalendar calendar = (GameCalendar)w.get(ITEM.CALENDAR);
GameTime currentTime = w.currentTime();
int currentYear = calendar.getYear(currentTime.getTicks());
int lastyear = currentYear - 1;
int ticksAtStartOfyear = calendar.getTicks(currentYear);
int ticksAtStartOfLastYear = calendar.getTicks(lastyear);
GameTime[] interval = {new GameTime(ticksAtStartOfLastYear), new GameTime(ticksAtStartOfyear)};
TransactionAggregator aggregator = new TransactionAggregator(w, pr){
@Override
protected boolean condition(int transactionID) {
Transaction t = super.w.getTransaction(super.principal,
transactionID);
if (t instanceof AddItemTransaction) {
// Since buying something is just converting one asset type to
// another.
return false;
}
return true;
}
};
aggregator.setTimes(interval);
return aggregator.calculateValue().getAmount();
}

testActivityLists

Class: jfreerails.world.top.WorldImplTest

Documentation

No documentation available

Source Code

public void testActivityLists() {
World w = new WorldImpl();
Player player = new Player("Name", 0);
w.addPlayer(player);
FreerailsPrincipal principal = player.getPrincipal();
// Test adding activities.
assertEquals(0, w.size(principal));
Activity act = new TestActivity(30);
int actIndex = w.addActiveEntity(principal, act);
assertEquals(0, actIndex);
assertEquals(1, w.size(principal));
actIndex = w.addActiveEntity(principal, act);
assertEquals(1, actIndex);
assertEquals(2, w.size(principal));
// Then removing them.
Activity expected = new TestActivity(30);
assertEquals(expected, act);
Activity actual = w.removeLastActiveEntity(principal);
assertEquals(actual, expected);
assertEquals(1, w.size(principal));
}

getFixedCost

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

public Money getFixedCost() {
return properties.getFixedCost();
}

testStockHolderEquityFigure

Class: jfreerails.client.view.BalanceSheetGeneratorTest

Documentation

No documentation available

Source Code

public void testStockHolderEquityFigure() {
BalanceSheetGenerator generator = new BalanceSheetGenerator(world,
player.getPrincipal());
Money expectStockHolderEquity = new Money(-500000);
assertEquals(expectStockHolderEquity, generator.total.equity);
}

main

Class: jfreerails.controller.ReportBugTextGenerator

Documentation

No documentation available

Source Code

public static void main(String[] args) {
Exception e = genException();
System.out.println(genText());
System.out.println(genText(e));
}

getTileViewWithNumber

Class: jfreerails.client.top.RenderersRootImpl

Documentation

No documentation available

Source Code

public TileRenderer getTileViewWithNumber(int i) {
return tiles.getTileViewWithNumber(i);
}

get

Class: jfreerails.util.IntArray

Documentation

/**
* Retrieve the value present at an index position in the array.
*
* @param index
* index position for value to be retrieved
* @return value from position in the array
*/

Source Code

/**
* Retrieve the value present at an index position in the array.
*
* @param index
* index position for value to be retrieved
* @return value from position in the array
*/
public final int get(int index) {
if (index < countPresent) {
return baseArray[index];
}
throw new ArrayIndexOutOfBoundsException("Invalid index value");
}

Called Methods

No outgoing method calls

main

Class: jfreerails.world.train.IntLineTest

Documentation

No documentation available

Source Code

public static void main(String[] args) {
junit.textui.TestRunner.run(IntLineTest.class);
}

Called Methods

No outgoing method calls

getTerrainTypeName

Class: jfreerails.world.terrain.NullTerrainType

Documentation

No documentation available

Source Code

public String getTerrainTypeName() {
return "null";
}

Called Methods

No outgoing method calls

MainMapAndOverviewMapMediator

Class: jfreerails.client.view.MainMapAndOverviewMapMediator

Documentation

No documentation available

Source Code

public MainMapAndOverviewMapMediator(JComponent omv, JViewport v,
JComponent mm, Rectangle rect) {
setup(omv, v, mm, rect);
}

getCause

Class: jfreerails.move.WorldDiffMove

Documentation

No documentation available

Source Code

public Cause getCause() {
return cause;
}

Called Methods

No outgoing method calls

size

Class: jfreerails.controller.OpenList

Documentation

No documentation available

Source Code

int size() {
return queue.size();
}

Called Methods

No outgoing method calls

previous

Class: jfreerails.world.top.WorldIterator

Documentation

/**
* Moves the cursor up one row from its current position.
*/

Source Code

/**
* Moves the cursor up one row from its current position.
*/
boolean previous();

Called Methods

No outgoing method calls

testSharedLists

Class: jfreerails.world.top.WorldDiffsTest

Documentation

No documentation available

Source Code

public void testSharedLists() {
WorldImpl underlyingWorld = new WorldImpl(10, 10);
CargoType mailCT = new CargoType(10, "Mail", Categories.Mail);
CargoType passengersCT = new CargoType(10, "Passengers",
Categories.Passengers);
underlyingWorld.add(SKEY.CARGO_TYPES, mailCT);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(0, worldDiff.listDiffs());
assertEquals(1, worldDiff.size(SKEY.CARGO_TYPES));
FreerailsSerializable f = worldDiff.get(SKEY.CARGO_TYPES, 0);
assertEquals("The mail cargotype should be accessible.", mailCT, f);
worldDiff.add(SKEY.CARGO_TYPES, passengersCT);
assertEquals(2, worldDiff.size(SKEY.CARGO_TYPES));
assertEquals("2 Diffs: the length of the list + the actual element", 2,
worldDiff.listDiffs());
f = worldDiff.removeLast(SKEY.CARGO_TYPES);
assertEquals(passengersCT, f);
assertEquals(0, worldDiff.listDiffs());
f = worldDiff.removeLast(SKEY.CARGO_TYPES);
assertEquals(mailCT, f);
assertEquals("1 Diff: the list length.", 1, worldDiff.listDiffs());
assertEquals(0 , worldDiff.size(SKEY.CARGO_TYPES));
worldDiff.add(SKEY.CARGO_TYPES, mailCT);
assertEquals(0, worldDiff.listDiffs());
worldDiff.set(SKEY.CARGO_TYPES, 0, passengersCT);
assertEquals("1 Diff: element 0", 1, worldDiff.listDiffs());
}

removeDisplayModesBelow

Class: jfreerails.client.view.DisplayModesComboBoxModels

Documentation

/**
* Permanently removes from the list in this object any display modes with
* width, height, or bitdepth below the specified values.
*/

Source Code

/**
* Permanently removes from the list in this object any display modes with
* width, height, or bitdepth below the specified values.
*/
public void removeDisplayModesBelow(int width, int height, int bitdepth) {
Iterator<MyDisplayMode> it = modes.iterator();
while (it.hasNext()) {
MyDisplayMode mode = it.next();
DisplayMode displayMode = mode.displayMode;
final boolean tooNarrow = displayMode.getWidth() < width;
final boolean tooShort = displayMode.getHeight() < height;
/*
* Note, displayMode.getBitDepth() may return
* DisplayMode.BIT_DEPTH_MULTI, which is -1.
*/
final boolean tooFewColours = (displayMode.getBitDepth() < bitdepth)
&& (displayMode.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI);
if (tooNarrow || tooShort || tooFewColours) {
it.remove();
}
}
}

Called Methods

No outgoing method calls

calculateValues

Class: jfreerails.world.top.TransactionAggregator

Documentation

/**
* Returns the sum of the appropriate transactions up to (inclusive) each of
* the specified times. Do not override.
*/

Source Code

/**
* Returns the sum of the appropriate transactions up to (inclusive) each of
* the specified times. Do not override.
*/
final public Money[] calculateValues() {
setTotalsArrayLength(timeValues.length - 1);
int timeIndex = 0;
int numberOfTransactions = w.getNumberOfTransactions(this.principal);
setTotalsArrayLength(timeValues.length - 1);
for (int i = 0; i < numberOfTransactions; i++) {
GameTime time = w.getTransactionTimeStamp(principal, i);
int transactionTime = time.getTicks();
while (timeValues[timeIndex].getTicks() <= transactionTime) {
storeTotalIfAppropriate(timeIndex);
timeIndex++;
if (timeIndex >= timeValues.length) {
/*
* The current transaction occurred after the last of the
* specified times.
*/
return monetaryTotals;
}
}
if (timeIndex > 0 && condition(i)) {
incrementRunningTotal(i);
}
}
/*
* There are no more transactions and the last transaction occurred
* before one or more of the specified times.
*/
while (timeIndex < timeValues.length) {
storeTotalIfAppropriate(timeIndex);
timeIndex++;
}
return monetaryTotals;
}

testNetWorth

Class: jfreerails.controller.StockPriceCalculatorTest

Documentation

No documentation available

Source Code

/*
* Test method for
* 'jfreerails.controller.StockPriceCalculator.netWorth(int)'
*/
public void testNetWorth() {
long initialNetworth = 500000;
assertEquals(initialNetworth, calc.netWorth(0));
int currentTicks = w.currentTime().getTicks();
GameTime newTime = new GameTime(currentTicks + 1);
w.setTime(newTime);
CargoBatch batch = new CargoBatch(0, 0, 0, 0, 0);
long income = 100000;
Transaction t = new DeliverCargoReceipt(new Money(income), 10, 0,
batch, 0);
FreerailsPrincipal princ = w.getPlayer(0).getPrincipal();
w.addTransaction(princ, t);
assertEquals(initialNetworth, calc.netWorth(0));
GameCalendar calendar = (GameCalendar) w.get(ITEM.CALENDAR);
int tpy = calendar.getTicksPerYear();
currentTicks = w.currentTime().getTicks();
newTime = new GameTime(currentTicks + tpy);
w.setTime(newTime);
long expectedNetWorth = initialNetworth + income;
assertEquals(expectedNetWorth, calc.netWorth(0));
}

CalcCargoSupplyRateAtStation

Class: jfreerails.controller.CalcCargoSupplyRateAtStation

Documentation

/**
* Call this constructor if the station does not exist yet.
*
* @param trackRuleNo
* the station type.
*/

Source Code

/**
* Call this constructor if the station does not exist yet.
*
* @param trackRuleNo
* the station type.
*/
public CalcCargoSupplyRateAtStation(ReadOnlyWorld world, int X, int Y,
int trackRuleNo) {
this.w = world;
this.x = X;
this.y = Y;
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, trackRuleNo);
stationRadius = trackRule.getStationRadius();
supplies = new Vector<CargoElementObject>();
populateSuppliesVector();
int numCargoTypes = w.size(SKEY.CARGO_TYPES);
demand = new int[numCargoTypes];
converts = ConvertedAtStation.emptyConversionArray(numCargoTypes);
}

TestState

Class: jfreerails.world.top.TestState

Documentation

No documentation available

Source Code

public TestState(int x) {
this.x = x;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result = 0;
// TODO is there are danger of overflow here?
for (int i = 0; i < xpoints.size(); i++) {
result = 29 * result + xpoints.get(i);
}
for (int i = 0; i < ypoints.size(); i++) {
result = 29 * result + ypoints.get(i);
}
return result;
}

hasNext

Class: jfreerails.world.common.ActivityIterator

Documentation

No documentation available

Source Code

boolean hasNext();

Called Methods

No outgoing method calls

getTrackPieceView

Class: jfreerails.client.renderer.MyRenderersRoot

Documentation

No documentation available

Source Code

@Override
public TrackPieceRenderer getTrackPieceView(int i) {
throw new UnsupportedOperationException("Not supported yet.");
}

Called Methods

No outgoing method calls

BrokerJFrame

Class: jfreerails.client.view.BrokerJFrame

Documentation

/** Creates new form BrokerJFrame */

Source Code

/** Creates new form BrokerJFrame */
BrokerJFrame() {
initComponents();
}

display

Class: jfreerails.client.view.TrainListCellRenderer

Documentation

No documentation available

Source Code

public void display(int newTrainNumber, int newScheduleOrderID) {
showingOrder = true;
this.trainNumber = newTrainNumber;
this.scheduleOrderNumber = newScheduleOrderID;
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS, trainNumber);
this.scheduleID = train.getScheduleID();
ImmutableSchedule s = (ImmutableSchedule) w.get(principal, KEY.TRAIN_SCHEDULES, scheduleID);
TrainOrdersModel order = s.getOrder(newScheduleOrderID);
// Set up the array of images.
if (null != order.consist) {
display(train.getEngineType(), order.consist);
} else {
images = new Image[0];
}
resetPreferredSize();
}

getMaintenance

Class: jfreerails.world.train.EngineType

Documentation

No documentation available

Source Code

public Money getMaintenance() {
return maintenance;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.cargo.CargoType

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = unitWeight;
result = 29 * result + category.hashCode();
result = 29 * result + name.hashCode();
return result;
}

Called Methods

No outgoing method calls

disconnect

Class: jfreerails.network.Connection2Server

Documentation

/**
* Disconnect from the server. When this method returns, calling isOpen() on
* this object returns false <b>and</b> calling isOpen() on the
* corresponding Connection2Client held by the server also returns false.
*
* @throws IOException
*/

Source Code

/**
* Disconnect from the server. When this method returns, calling isOpen() on
* this object returns false <b>and</b> calling isOpen() on the
* corresponding Connection2Client held by the server also returns false.
*
* @throws IOException
*/
void disconnect() throws IOException;

Called Methods

No outgoing method calls

setType

Class: jfreerails.world.top.ItemsTransactionAggregator

Documentation

No documentation available

Source Code

public void setType(int type) {
this.type = type;
}

Called Methods

No outgoing method calls

sendMove

Class: jfreerails.controller.TrackMoveProducer

Documentation

No documentation available

Source Code

private MoveStatus sendMove(Move m) {
MoveStatus ms = executor.doMove(m);
if (ms.isOk()) {
clearStackIfStale();
moveStack.add(m);
}
return ms;
}

assertBundlesNotEqual

Class: jfreerails.world.cargo.CargoBundleTest

Documentation

No documentation available

Source Code

private void assertBundlesNotEqual(MutableCargoBundle a,
MutableCargoBundle b) {
assertFalse(a.equals(b));
assertFalse(b.equals(a));
assertFalse(a.toImmutableCargoBundle().equals(b));
assertFalse(a.toImmutableCargoBundle().equals(
b.toImmutableCargoBundle()));
assertFalse(a.equals(b.toImmutableCargoBundle()));
}

testReverting2OriginalState2

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

public void testReverting2OriginalState2(){
underlying.addD1();
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
diffs.addD1();
diffs.addD2(2, String.valueOf(3));
diffs.addD2(2, String.valueOf(33));
assertEquals(2, diffs.sizeD2(2));
assertEquals(String.valueOf(3), diffs.get(2, 0));
assertEquals(String.valueOf(33), diffs.get(2, 1));
Object removed = diffs.removeLastD2(2);
assertEquals(String.valueOf(33), removed);
removed = diffs.removeLastD2(2);
assertEquals(String.valueOf(3), removed);
assertEquals(0, diffs.sizeD2(2));
assertEquals(3, diffs.sizeD1());
assertEquals(0, diffs.sizeD2(2));
diffs.removeLastD1();
assertEquals(2, diffs.sizeD1());
assertEquals(2, underlying.sizeD1());
assertEquals(0, map.size());
}

defensiveCopy

Class: jfreerails.world.top.World

Documentation

/**
* Returns a copy of this world object - making changes to this copy will
* not change this object.
*/

Source Code

/**
* Returns a copy of this world object - making changes to this copy will
* not change this object.
*/
World defensiveCopy();

Called Methods

No outgoing method calls

newBlankImage

Class: jfreerails.client.common.ImageManagerImpl

Documentation

No documentation available

Source Code

public Image newBlankImage(int height, int width) {
Image compatibleImage = defaultConfiguration.createCompatibleImage(
width, height, Transparency.TRANSLUCENT);
return compatibleImage;
}

Called Methods

No outgoing method calls

test3

Class: jfreerails.controller.BuildTrackExplorerTest

Documentation

/** Test for illegal track configurations. */

Source Code

/** Test for illegal track configurations. */
public void test3() {
// Build some track, from 10, 10 diagonally SE.
int y = 10;
int x = 10;
for (int i = 0; i < 4; i++) {
Step v = Step.SOUTH_EAST;
buildTrack(x, y, v);
x += v.deltaX;
y += v.deltaY;
}
// If we enter 10, 10 from the south, we should be able to build track S
// & SW.
PositionOnTrack start = PositionOnTrack.createComingFrom(10, 10,
Step.SOUTH);
BuildTrackExplorer explorer = new BuildTrackExplorer(world, principal);
explorer.setPosition(start.toInt());
// SE is going along existing track
assertNextVertexIs(Step.SOUTH_EAST, 11, 11, explorer);
// S is building new track.
assertNextVertexIs(Step.SOUTH, 10, 11, explorer);
assertFalse(explorer.hasNextEdge());
// If we enter 10, 11 from the north, we should be able to build track
// N, E, W, & NW.
start = PositionOnTrack.createComingFrom(10, 11, Step.NORTH);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.NORTH, 10, 10, explorer);
assertNextVertexIs(Step.EAST, 11, 11, explorer);
assertNextVertexIs(Step.WEST, 9, 11, explorer);
assertNextVertexIs(Step.NORTH_WEST, 9, 10, explorer);
assertFalse(explorer.hasNextEdge());
// If we enter 10, 12 from the north, we also should be able to build
// track N, E, W, & NW.
start = PositionOnTrack.createComingFrom(10, 12, Step.NORTH);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.NORTH, 10, 11, explorer);
assertNextVertexIs(Step.EAST, 11, 12, explorer);
assertNextVertexIs(Step.WEST, 9, 12, explorer);
assertNextVertexIs(Step.NORTH_WEST, 9, 11, explorer);
assertFalse(explorer.hasNextEdge());
}

doMove

Class: jfreerails.move.AddTransactionMove

Documentation

No documentation available

Source Code

public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.ok) {
w.addTransaction(this.principal, this.transaction);
}
return ms;
}

List1DImpl

Class: jfreerails.util.List1DImpl

Documentation

No documentation available

Source Code

public List1DImpl() {
elementData = new ArrayList<T>();
}

Called Methods

No outgoing method calls

removeLastList

Class: jfreerails.util.ListXDDiffs

Documentation

No documentation available

Source Code

int removeLastList(int... dim) {
int last = size(dim) - 1;
// Check that the list we are removing is empty.
int[] array = add2Array(dim, last);
if (0 != size(array))
throw new IllegalStateException();
ListKey sizeKeyB = new ListKey(ListKey.Type.EndPoint, listID, array);
diffs.remove(sizeKeyB);
setSize(last, dim);
return last;
}

getPrincipal

Class: jfreerails.controller.MoveExecutor

Documentation

No documentation available

Source Code

FreerailsPrincipal getPrincipal();

Called Methods

No outgoing method calls

getServerDetails

Class: jfreerails.network.InetConnection2Server

Documentation

No documentation available

Source Code

public String getServerDetails() {
return serverDetails;
}

Called Methods

No outgoing method calls

checkCalcT

Class: jfreerails.world.train.ConstAccTest

Documentation

No documentation available

Source Code

private static void checkCalcT(SpeedAgainstTime sat, double s){
boolean exceptionExpected = (s < 0) || ( s > sat.getS());
try{
double actualT = sat.calcT(s);
assertTrue(actualT >= 0);
assertTrue(actualT <= sat.getT());
assertFalse(exceptionExpected);
}catch (IllegalArgumentException e) {
assertTrue(exceptionExpected);
}
}

getIndex

Class: jfreerails.move.ChangeItemInListMove

Documentation

No documentation available

Source Code

public int getIndex() {
return index;
}

Called Methods

No outgoing method calls

addClip

Class: jfreerails.client.common.SoundManager

Documentation

No documentation available

Source Code

public void addClip(String s) throws IOException,
UnsupportedAudioFileException, LineUnavailableException {
if (samples.containsKey(s)) {
return;
}
URL url = getClass().getResource(s);
AudioInputStream audioInputStream = AudioSystem
.getAudioInputStream(loadStream(url.openStream()));
Sample sample = new Sample();
sample.format = audioInputStream.getFormat();
sample.size = (int) (sample.format.getFrameSize() * audioInputStream
.getFrameLength());
sample.audio = new byte[sample.size];
sample.info = new DataLine.Info(Clip.class, sample.format, sample.size);
audioInputStream.read(sample.audio, 0, sample.size);
samples.put(s, sample);
}

SpecialTileRenderer

Class: jfreerails.client.renderer.SpecialTileRenderer

Documentation

No documentation available

Source Code

public SpecialTileRenderer(ImageManager imageManager, int[] rgbValues,
TerrainType tileModel, TileRenderer parentTileView)
throws IOException {
super(tileModel, rgbValues);
this.setTileIcons(new Image[1]);
this.getTileIcons()[0] = imageManager.getImage(generateFilename());
this.parentTileView = parentTileView;
}

smallestF

Class: jfreerails.controller.OpenList

Documentation

No documentation available

Source Code

int smallestF() {
OpenListEntry entry = queue.peek();
return entry.f;
}

Called Methods

No outgoing method calls

ChangeCargoBundleMove

Class: jfreerails.move.ChangeCargoBundleMove

Documentation

No documentation available

Source Code

public ChangeCargoBundleMove(ImmutableCargoBundle before,
ImmutableCargoBundle after, int bundleNumber, FreerailsPrincipal p) {
super(KEY.CARGO_BUNDLES, bundleNumber, before, after, p);
}

steps

Class: jfreerails.world.train.PathOnTiles

Documentation

No documentation available

Source Code

public int steps() {
return vectors.size();
}

setWaitUntilFull

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void setWaitUntilFull(boolean b) {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
// If auto-consist is set do nothing
if (oldOrders.autoConsist)
return;
// If no-change is set do nothing
if (oldOrders.consist == null)
return;
boolean autoConsist = false;
newOrders = new TrainOrdersModel(oldOrders.getStationID(),
oldOrders.consist, b, autoConsist);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}

ClientOptionsJPanel

Class: jfreerails.launcher.ClientOptionsJPanel

Documentation

No documentation available

Source Code

public ClientOptionsJPanel(LauncherInterface owner) {
this.owner = owner;
initComponents();
listModel = new DisplayModesComboBoxModels();
listModel.removeDisplayModesBelow(640, 480, 16);
jList1.setModel(listModel);
jList1.setSelectedIndex(0);
validateInput();
// Listen for changes in the server port text box.
remotePort.getDocument().addDocumentListener(documentListener);
remoteIP.getDocument().addDocumentListener(documentListener);
playerName.getDocument().addDocumentListener(documentListener);
}

nextBondInterestRate

Class: jfreerails.controller.FinancialDataGatherer

Documentation

No documentation available

Source Code

public int nextBondInterestRate() {
EconomicClimate ec = (EconomicClimate) w.get(ITEM.ECONOMIC_CLIMATE);
return bonds + ec.getBaseInterestRate();
}

resizeCopy

Class: jfreerails.util.GrowableBase

Documentation

/**
* Copy data after array resize. This default implementation just copies the
* entire contents of the old array to the start of the new array. It should
* be overridden in cases where data needs to be rearranged in the array
* after a resize.
*
* @param base
* original array containing data
* @param grown
* resized array for data
*/

Source Code

/**
* Copy data after array resize. This default implementation just copies the
* entire contents of the old array to the start of the new array. It should
* be overridden in cases where data needs to be rearranged in the array
* after a resize.
*
* @param base
* original array containing data
* @param grown
* resized array for data
*/
protected void resizeCopy(Object base, Object grown) {
System.arraycopy(base, 0, grown, 0, Array.getLength(base));
}

Called Methods

No outgoing method calls

refreshTile

Class: jfreerails.client.renderer.ZoomedOutMapRenderer

Documentation

No documentation available

Source Code

private void refreshTile(Point tile) {
FreerailsTile tt = (FreerailsTile) w.getTile(tile.x, tile.y);
if (tt.getTrackPiece().equals(NullTrackPiece.getInstance())) {
int typeNumber = tt.getTerrainTypeID();
TerrainType terrainType = (TerrainType) w.get(SKEY.TERRAIN_TYPES,
typeNumber);
one2oneImage.setRGB(tile.x, tile.y, terrainType.getRGB());
} else {
/* black with alpha of 1 */
one2oneImage.setRGB(tile.x, tile.y, 0xff000000);
}
isDirty = true;
// int scaledX = (tile.x - mapX) * imageWidth / mapWidth;
// int scaledY = (tile.y - mapY) * imageHeight / mapHeight;
// int minx = scaledX < 2 ? 0 : scaledX - 2;
// int miny = scaledY < 2 ? 0 : scaledY - 2;
// int maxx = scaledX > imageWidth - 4 ? imageWidth : scaledX + 4;
// int maxy = scaledY > imageHeight - 4 ? imageHeight : scaledY + 4;
// mapGraphics.setClip(minx, miny, maxx - minx, maxy - miny);
// mapGraphics.clearRect(minx, miny, maxx - minx, maxy - miny);
// mapGraphics.drawImage(one2oneImage, affineTransform, null);
}

end_TrackSet

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* A container element end event handling method.
*/

Source Code

/**
* A container element end event handling method.
*/
void end_TrackSet() throws SAXException;

Called Methods

No outgoing method calls

populateSuppliesVector

Class: jfreerails.controller.CalcCargoSupplyRateAtStation

Documentation

No documentation available

Source Code

private void populateSuppliesVector() {
// fill supplies vector with 0 values for all cargo types
// get the correct list of cargoes from the world object
CargoElementObject tempCargoElement;
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
// cT = (CargoType) w.get(SKEY.CARGO_TYPES, i);
tempCargoElement = new CargoElementObject(0, i);
supplies.add(tempCargoElement);
}
}

generateFilename

Class: jfreerails.client.renderer.SpecialTileRenderer

Documentation

No documentation available

Source Code

private String generateFilename() {
return "terrain" + File.separator + this.getTerrainType() + ".png";
}

isOpen

Class: jfreerails.network.InetConnection

Documentation

No documentation available

Source Code

synchronized boolean isOpen() {
boolean isClosed = socket.isClosed();
return !isClosed;
}

Called Methods

No outgoing method calls

addOverviewmapzoomMenuItem

Class: experimental.SimpleComponentFactoryImpl2

Documentation

No documentation available

Source Code

private void addOverviewmapzoomMenuItem(JMenu displayMenu, final float scale) {
String menuItemName = "Set overview map scale=" + scale;
JMenuItem menuItem = new JMenuItem(menuItemName);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
overviewMap.setup(new BlankMapRenderer(scale));
}
});
displayMenu.add(menuItem);
}

addResourceTile

Class: jfreerails.server.CityTilePositioner

Documentation

No documentation available

Source Code

private void addResourceTile(CityEconomicModel city) {
int tileTypeNo = random.nextInt(resourceTerrainTypes.size());
TerrainType type = resourceTerrainTypes.get(tileTypeNo);
city.addTile(type);
}

nextSegment

Class: jfreerails.world.common.FreerailsPathIteratorImpl

Documentation

No documentation available

Source Code

public void nextSegment(IntLine line) {
if (hasNext()) {
Point a;
Point b;
if (forwards) {
position++;
a = points.get(position - 1);
b = points.get(position);
} else {
position--;
a = points.get(position + 1);
b = points.get(position);
}
line.x1 = a.x;
line.y1 = a.y;
line.x2 = b.x;
line.y2 = b.y;
} else {
throw new NoSuchElementException();
}
}

testIsOpen

Class: jfreerails.network.LocalConnectionTest

Documentation

No documentation available

Source Code

public void testIsOpen() {
assertTrue(localConnection.isOpen());
}

size

Class: jfreerails.world.cargo.CargoBundle

Documentation

No documentation available

Source Code

int size();

Called Methods

No outgoing method calls

buildTrain

Class: jfreerails.server.TrainUpdater

Documentation

No documentation available

Source Code

public void buildTrain(int engineTypeId, ImInts wagons, ImPoint p,
FreerailsPrincipal principal, ReadOnlyWorld world) {
// If there are no wagons, setup an automatic schedule.
boolean autoSchedule = 0 == wagons.size();
ImmutableSchedule is = generateInitialSchedule(principal, world,
autoSchedule);
PreMove addTrain = new AddTrainPreMove(engineTypeId, wagons, p,
principal, is);
Move m = addTrain.generateMove(world);
moveReceiver.processMove(m);
}

getCopyOfWorld

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

World getCopyOfWorld() {
return this.getWorld().defensiveCopy();
}

getMapHeight

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public int getMapHeight() {
if (map.length == 0) {
// When the map size is 0*0 we get a
// java.lang.ArrayIndexOutOfBoundsException: 0
// if we don't have the check above.
return 0;
}
return map[0].length;
}

Called Methods

No outgoing method calls

getName

Class: jfreerails.world.cargo.CargoType

Documentation

No documentation available

Source Code

public String getName() {
return name;
}

Called Methods

No outgoing method calls

start_Tiles

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void start_Tiles(final Attributes meta) throws SAXException {
}

Called Methods

No outgoing method calls

testEquals

Class: jfreerails.world.top.WorldImplTest

Documentation

No documentation available

Source Code

public void testEquals() {
World original;
World copy;
original = new WorldImpl();
copy = original.defensiveCopy();
Player player = new Player("Name", 0);
int index = copy.addPlayer(player);
assertEquals(index, 0);
assertFalse(copy.equals(original));
original.addPlayer(player);
assertEquals("The copies should be logically equal.", original, copy);
assertTrue(Utils.equalsBySerialization(original, copy));
Transaction t = new Receipt(new Money(100),
Transaction.Category.MISC_INCOME);
copy.addTransaction(player.getPrincipal(), t);
assertEquals(new Money(100), copy.getCurrentBalance(player
.getPrincipal()));
assertFalse(copy.equals(original));
}

remove

Class: jfreerails.util.ArrayBase

Documentation

/**
* Remove a value from the array. All values above the index removed are
* moved down one index position.
*
* @param index
* index number of value to be removed
*/

Source Code

/**
* Remove a value from the array. All values above the index removed are
* moved down one index position.
*
* @param index
* index number of value to be removed
*/
public void remove(int index) {
remove(index, index + 1);
}

SetTargetTicksPerSecondAction

Class: jfreerails.client.view.SetTargetTicksPerSecondAction

Documentation

/**
* Same as the constructor above but it enables also to associate a
* <code>keyEvent</code> with the action.
*
* @param name
* action name
* @param speed
* speed
* @param keyEvent
* associated key event. Use values from
* <code>KeyEvent</class>.
*
* by MystiqueAgent
*/

Source Code

/**
* Same as the constructor above but it enables also to associate a
* <code>keyEvent</code> with the action.
*
* @param name
* action name
* @param speed
* speed
* @param keyEvent
* associated key event. Use values from
* <code>KeyEvent</class>.
*
* by MystiqueAgent
*/
public SetTargetTicksPerSecondAction(String name, int speed,
int keyEvent) {
putValue(NAME, name);
this.speed = speed;
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(keyEvent, 0));
}

Called Methods

No outgoing method calls

characters

Class: jfreerails.server.parser.Track_TilesParser

Documentation

No documentation available

Source Code

public void characters(char[] chars, int start, int len)
throws SAXException {
buffer.append(chars, start, len);
}

Called Methods

No outgoing method calls

changeTreasuryStock

Class: jfreerails.controller.FinancialDataGatherer

Documentation

No documentation available

Source Code

public void changeTreasuryStock(int deltaStock) {
}

Called Methods

No outgoing method calls

disconnect

Class: jfreerails.network.AbstractInetConnection

Documentation

No documentation available

Source Code

public void disconnect() throws IOException {
logger.fine(this + "Initiating shutdown..");
shutdownOutput();
long waitUntil = System.currentTimeMillis() + timeout;
synchronized (readerThreadStatus) {
while (readerThreadStatus.isOpen()) {
long currentTime = System.currentTimeMillis();
if (currentTime >= waitUntil) {
shutDownInput();
throw new IOException(
"Time-out while trying to disconnect.");
}
try {
readerThreadStatus.wait(timeout);
} catch (InterruptedException e) {
// do nothing.
}
}
}
logger.fine(this + "Finished shutdown!! --status="
+ String.valueOf(status.isOpen()));
}

generateMove

Class: jfreerails.move.ChangeTrainMove

Documentation

No documentation available

Source Code

public static ChangeTrainMove generateMove(int id, TrainModel before,
int newEngine, ImInts newWagons, FreerailsPrincipal p) {
TrainModel after = before.getNewInstance(newEngine, newWagons);
return new ChangeTrainMove(id, before, after, p);
}

equals

Class: jfreerails.world.accounts.AddItemTransaction

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object obj) {
if (obj instanceof AddItemTransaction) {
AddItemTransaction test = (AddItemTransaction) obj;
return this.amount.equals(test.amount) && category == test.category
&& type == test.type && quantity == test.quantity;
}
return false;
}

CalcCargoSupplyRateAtStation

Class: jfreerails.controller.CalcCargoSupplyRateAtStation

Documentation

/** Call this constructor if the station already exists. */

Source Code

/** Call this constructor if the station already exists. */
public CalcCargoSupplyRateAtStation(ReadOnlyWorld world, int X, int Y) {
this(world, X, Y, findTrackRule(X, Y, world));
}

getTicksPerYear

Class: jfreerails.world.common.GameCalendar

Documentation

No documentation available

Source Code

public int getTicksPerYear() {
return ticksPerYear;
}

Called Methods

No outgoing method calls

Pair

Class: jfreerails.util.Pair

Documentation

No documentation available

Source Code

public Pair(A e1, B e2) {
this.e1 = e1;
this.e2 = e2;
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.world.terrain.CityModel

Documentation

No documentation available

Source Code

@Override
public String toString() {
return name+" "+x+", "+y;
}

Called Methods

No outgoing method calls

update

Class: jfreerails.server.CargoAtStationsGenerator

Documentation

/** Call this method once a month. */

Source Code

/** Call this method once a month. */
public void update(World w, MoveReceiver moveReceiver) {
for (int k = 0; k < w.getNumberOfPlayers(); k++) {
FreerailsPrincipal principal = w.getPlayer(k).getPrincipal();
NonNullElements nonNullStations = new NonNullElements(KEY.STATIONS,
w, principal);
while (nonNullStations.next()) {
StationModel station = (StationModel) nonNullStations
.getElement();
SupplyAtStation supply = station.getSupply();
ImmutableCargoBundle cargoBundle = (ImmutableCargoBundle) w
.get(principal, KEY.CARGO_BUNDLES,
station.getCargoBundleID());
MutableCargoBundle before = new MutableCargoBundle(cargoBundle);
MutableCargoBundle after = new MutableCargoBundle(cargoBundle);
int stationNumber = nonNullStations.getIndex();
/*
* Get the iterator from a copy to avoid a
* ConcurrentModificationException if the amount gets set to
* zero and the CargoBatch removed from the cargo bundle. LL
*/
Iterator<CargoBatch> it = after.toImmutableCargoBundle()
.cargoBatchIterator();
while (it.hasNext()) {
CargoBatch cb = it.next();
int amount = after.getAmount(cb);
if (amount > 0) {
// (23/24)^12 = 0.60
after.setAmount(cb, amount * 23 / 24);
}
}
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
int amountSupplied = supply.getSupply(i);
if (amountSupplied > 0) {
CargoBatch cb = new CargoBatch(i, station.x, station.y,
0, stationNumber);
int amountAlready = after.getAmount(cb);
// Obtain the month
GameTime time = w.currentTime();
GameCalendar calendar = (GameCalendar) w
.get(ITEM.CALENDAR);
int month = calendar.getMonth(time.getTicks());
int amountAfter = calculateAmountToAdd(amountSupplied,
month)
+ amountAlready;
after.setAmount(cb, amountAfter);
}
}
Move m = new ChangeCargoBundleMove(before
.toImmutableCargoBundle(), after
.toImmutableCargoBundle(), station.getCargoBundleID(),
principal);
moveReceiver.processMove(m);
}
}
}

overridesHashCodeAndEquals

Class: experimental.CheckFreerailsSerializableClasses

Documentation

No documentation available

Source Code

static boolean overridesHashCodeAndEquals(Class clazz) {
try {
boolean okSoFar = true;
Method equals = clazz.getMethod("equals", Object.class);
if (equals.getDeclaringClass().equals(Object.class)) {
System.err.println(clazz.getName() + " does not override "
+ equals.getName());
okSoFar = false;
}
Method hashCode = clazz.getMethod("hashCode");
if (hashCode.getDeclaringClass().equals(Object.class)) {
System.err.println(clazz.getName() + " does not override "
+ hashCode.getName());
okSoFar = false;
}
return okSoFar;
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}

Called Methods

No outgoing method calls

stop

Class: jfreerails.network.EchoGameServer

Documentation

No documentation available

Source Code

public synchronized void stop() {
status.close();
for (int i = 0; i < connections.size(); i++) {
AbstractInetConnection connection = (AbstractInetConnection) connections
.get(i);
if (connection.isOpen()) {
try {
connection.setTimeOut(0);
connection.disconnect();
} catch (Exception e) {
// Do nothing.
}
}
}
}

getListID

Class: jfreerails.util.ListKey

Documentation

No documentation available

Source Code

public Enum getListID() {
return listID;
}

Called Methods

No outgoing method calls

getOutput

Class: jfreerails.world.terrain.Conversion

Documentation

No documentation available

Source Code

public int getOutput() {
return output;
}

Called Methods

No outgoing method calls

handle_Consumes

Class: jfreerails.server.parser.CargoAndTerrainHandlerImpl

Documentation

No documentation available

Source Code

public void handle_Consumes(final Attributes meta) throws SAXException {
int cargoConsumed = string2CargoID(meta.getValue("Cargo"));
String prerequisiteString = meta.getValue("Prerequisite");
// "Prerequisite" is an optional attribute, so may be null.
int prerequisiteForConsumption = (null == prerequisiteString ? 1
: Integer.parseInt(prerequisiteString));
Consumption consumption = new Consumption(cargoConsumed,
prerequisiteForConsumption);
typeConsumes.add(consumption);
}

itemRemoved

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

public void itemRemoved(KEY key, int index, FreerailsPrincipal principal) {
// do nothing
}

Called Methods

No outgoing method calls

getServerPort

Class: jfreerails.launcher.SelectMapJPanel

Documentation

No documentation available

Source Code

int getServerPort() {
String s = serverPort.getText();
return Integer.parseInt(s);
}

Called Methods

No outgoing method calls

dumpImages

Class: jfreerails.client.top.SimpleTileRenderer

Documentation

No documentation available

Source Code

public void dumpImages(ImageManager imageManager) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}

Called Methods

No outgoing method calls

processStationBundle

Class: jfreerails.controller.DropOffAndPickupCargoMoveGenerator

Documentation

/** Transfer cargo from the station to the train subject to the space available on the train.
*/

Source Code

/** Transfer cargo from the station to the train subject to the space available on the train.
*/
private void processStationBundle() {
ImInts spaceAvailable = TrainAccessor.spaceAvailable2(w, trainAfter.toImmutableCargoBundle(), consist);
for (int cargoType = 0; cargoType < spaceAvailable.size(); cargoType++) {
int quantity = spaceAvailable.get(cargoType);
int amount2transfer = Math.min(quantity, stationAfter
.getAmount(cargoType));
transferCargo(cargoType, amount2transfer, stationAfter, trainAfter);
}
}

getKey

Class: jfreerails.move.RemoveItemFromListMove

Documentation

No documentation available

Source Code

public KEY getKey() {
return listKey;
}

Called Methods

No outgoing method calls

testAddingActivateEntity

Class: jfreerails.move.WorldDiffsMoveTest

Documentation

No documentation available

Source Code

public void testAddingActivateEntity() {
Activity act = new TestActivity(30);
int row = world.addActiveEntity(fp1, act);
act = new TestActivity(40);
world.add(fp1, row, act);
act = new TestActivity(50);
diffs.add(fp1, row, act);
act = new TestActivity(60);
row = diffs.addActiveEntity(fp1, act);
act = new TestActivity(70);
diffs.add(fp1, row, act);
act = new TestActivity(80);
row = diffs.addActiveEntity(fp1, act);
act = new TestActivity(90);
diffs.add(fp1, row, act);
runTests();
}

totalShares

Class: jfreerails.controller.FinancialDataGatherer

Documentation

/** Returns The number of open Shares */

Source Code

/** Returns The number of open Shares */
public int totalShares() {
return totalShares;
}

Called Methods

No outgoing method calls

LRUCache

Class: jfreerails.util.LRUCache

Documentation

/**
* Creates a new LRU cache.
*
* @param cacheSize
* the maximum number of entries that will be kept in this cache.
*/

Source Code

/**
* Creates a new LRU cache.
*
* @param cacheSize
* the maximum number of entries that will be kept in this cache.
*/
public LRUCache(int cacheSize) {
this.cacheSize = cacheSize;
int hashTableCapacity = (int) Math
.ceil(cacheSize / hashTableLoadFactor) + 1;
map = new LinkedHashMap<K, V>(hashTableCapacity, hashTableLoadFactor,
true) {
// (an anonymous inner class)
private static final long serialVersionUID = 1;
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > LRUCache.this.cacheSize;
}
};
}

Called Methods

No outgoing method calls

getPosition

Class: jfreerails.controller.Map

Documentation

No documentation available

Source Code

public int getPosition() {
return this.position;
}

Called Methods

No outgoing method calls

mouseClicked

Class: jfreerails.client.view.StationPlacementCursor

Documentation

No documentation available

Source Code

@Override
public void mouseClicked(MouseEvent e) {
int button = e.getButton();
if (button == MouseEvent.BUTTON1) {
/* attempt to build */
stationBuildModel.getStationBuildAction().actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""));
} else if (button == MouseEvent.BUTTON3) {
/* cancel the build */
stationBuildModel.getStationCancelAction().actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""));
}
}

Called Methods

refreshTile

Class: jfreerails.client.renderer.BlankMapRenderer

Documentation

No documentation available

Source Code

public void refreshTile(int x, int y) {
}

Called Methods

No outgoing method calls

SimplePathIteratorImplTest

Class: jfreerails.world.train.SimplePathIteratorImplTest

Documentation

No documentation available

Source Code

public SimplePathIteratorImplTest(String arg0) {
super(arg0);
}

Called Methods

No outgoing method calls

setInfoText

Class: jfreerails.launcher.LauncherInterface

Documentation

No documentation available

Source Code

void setInfoText(String text, int status);

Called Methods

No outgoing method calls

setHeight

Class: jfreerails.client.view.TrainListCellRenderer

Documentation

No documentation available

Source Code

public void setHeight(int i) {
height = i;
}

Called Methods

No outgoing method calls

FreerailsClient

Class: jfreerails.network.specifics.FreerailsClient

Documentation

No documentation available

Source Code

public FreerailsClient() {
moveFork = new MoveChainFork();
}

Called Methods

No outgoing method calls

AddPlayerMove

Class: jfreerails.move.AddPlayerMove

Documentation

No documentation available

Source Code

private AddPlayerMove(Player p) {
player2add = p;
}

Called Methods

No outgoing method calls

getID

Class: jfreerails.world.top.TypeID

Documentation

No documentation available

Source Code

public int getID() {
return id;
}

Called Methods

No outgoing method calls

contains

Class: jfreerails.world.track.TrackConfiguration

Documentation

No documentation available

Source Code

public boolean contains(FlatTrackTemplate ftt) {
int trackTemplate = ftt.get9bitTemplate();
return contains(trackTemplate);
}

getDirection

Class: jfreerails.world.common.Step

Documentation

/**
*
* @return compass bearing in radians.
*/

Source Code

/**
*
* @return compass bearing in radians.
*/
public double getDirection() {
int i = 0;
while (this != list[i]) {
i++;
}
return 2 * Math.PI / 8 * i;
}

Called Methods

No outgoing method calls

endPrefixMapping

Class: jfreerails.server.parser.CargoAndTerrainParser

Documentation

/**
* This SAX interface method is implemented by the parser.
*
*/

Source Code

/**
* This SAX interface method is implemented by the parser.
*
*/
public final void endPrefixMapping(final java.lang.String prefix)
throws SAXException {
}

Called Methods

No outgoing method calls

use

Class: jfreerails.client.top.SynchronizedEventQueue

Documentation

No documentation available

Source Code

public static synchronized void use() {
if (!alreadyInUse) {
/* set up the synchronized event queue */
EventQueue eventQueue = Toolkit.getDefaultToolkit()
.getSystemEventQueue();
eventQueue.push(instance);
alreadyInUse = true;
}
}

Called Methods

No outgoing method calls

deltaCash

Class: jfreerails.world.accounts.AddItemTransaction

Documentation

No documentation available

Source Code

public Money deltaCash() {
return amount;
}

Called Methods

No outgoing method calls

tryDoMove

Class: experimental.SimpleMoveReceiver

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(Move move) {
return move.tryDoMove(w, Player.AUTHORITATIVE);
}

hashCode

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = properties.hashCode();
result = 29 * result + legalConfigurations.hashCode();
result = 29 * result + legalTrackPlacement.hashCode();
return result;
}

MyRenderersRoot

Class: jfreerails.client.renderer.MyRenderersRoot

Documentation

No documentation available

Source Code

public MyRenderersRoot() {
try {
this.trainImages = new TrainImages(imageManager, "mail");
} catch (IOException ex) {
Logger.getLogger(MyRenderersRoot.class.getName()).log(Level.SEVERE, null, ex);
fail();
}
}

Called Methods

No outgoing method calls

ImageManagerImpl

Class: jfreerails.client.common.ImageManagerImpl

Documentation

No documentation available

Source Code

public ImageManagerImpl(String readpath, String writePath) {
pathToReadFrom = readpath;
pathToWriteTo = writePath;
// Attempt to increase quality..
renderingHints = new RenderingHints(
RenderingHints.KEY_ALPHA_INTERPOLATION,
RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
renderingHints.put(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
renderingHints.put(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
}

Called Methods

No outgoing method calls

set

Class: jfreerails.util.List2D

Documentation

No documentation available

Source Code

void set(int d1, int d2, T element);

Called Methods

No outgoing method calls

getUndoneMove

Class: jfreerails.move.UndoMove

Documentation

No documentation available

Source Code

public Move getUndoneMove() {
return move2undo;
}

Called Methods

No outgoing method calls

initComponents

Class: jfreerails.launcher.SelectMapJPanel

Documentation

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/

Source Code

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
newmapsJList = new javax.swing.JList();
jPanel4 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
savedmapsJList = new javax.swing.JList();
jPanel3 = new javax.swing.JPanel();
portLabel = new javax.swing.JLabel();
serverPort = new javax.swing.JTextField();
jPanel2 = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel1.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), "New Game"));
jPanel1.setPreferredSize(null);
jScrollPane1.setViewportBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
newmapsJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
newmapsJList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
newmapsJListValueChanged(evt);
}
});
jScrollPane1.setViewportView(newmapsJList);
jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jPanel1, gridBagConstraints);
jPanel4.setLayout(new java.awt.BorderLayout());
jPanel4.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), "Load game"));
jPanel4.setPreferredSize(null);
jPanel4.setRequestFocusEnabled(false);
jScrollPane2.setViewportBorder(new javax.swing.border.BevelBorder(javax.swing.border.BevelBorder.LOWERED));
savedmapsJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
savedmapsJList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
savedmapsJListValueChanged(evt);
}
});
jScrollPane2.setViewportView(savedmapsJList);
jPanel4.add(jScrollPane2, java.awt.BorderLayout.CENTER);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jPanel4, gridBagConstraints);
jPanel3.setLayout(new java.awt.GridBagLayout());
jPanel3.setBorder(new javax.swing.border.TitledBorder(new javax.swing.border.EtchedBorder(), "Server port"));
portLabel.setText("Port:");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel3.add(portLabel, gridBagConstraints);
serverPort.setColumns(6);
serverPort.setText( owner.getProperty("freerails.server.port"));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel3.add(serverPort, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
jPanel3.add(jPanel2, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
add(jPanel3, gridBagConstraints);
}

setUp

Class: jfreerails.network.specifics.AbstractFreerailsServerTestCase

Documentation

No documentation available

Source Code

@Override
protected synchronized void setUp() throws Exception {
server = FreerailsGameServer
.startServer(new SavedGamesManager4UnitTests());
connectionAccepter = new InetConnectionAccepter(0, server);
Thread serverThread = new Thread(connectionAccepter);
serverThread.start();
}

isUpdateDue

Class: jfreerails.controller.MoveTrainPreMove

Documentation

/**
* Returns true iff an updated is due.
*
*/

Source Code

/**
* Returns true iff an updated is due.
*
*/
public boolean isUpdateDue(ReadOnlyWorld w) {
GameTime currentTime = w.currentTime();
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
ActivityIterator ai = w.getActivities(principal, trainID);
ai.gotoLastActivity();
double finishTime = ai.getFinishTime();
double ticks = currentTime.getTicks();
boolean hasFinishedLastActivity = Math.floor(finishTime) <= ticks;
TrainActivity trainActivity = ta.getStatus(finishTime);
if(trainActivity == TrainActivity.WAITING_FOR_FULL_LOAD){
//Check whether there is any cargo that can be added to the train.
ImInts spaceAvailable = ta.spaceAvailable();
int stationId = ta.getStationId(ticks);
if(stationId == -1)
throw new IllegalStateException();
StationModel station = (StationModel)w.get(principal, KEY.STATIONS, stationId);
CargoBundle cb = (CargoBundle)w.get(principal, KEY.CARGO_BUNDLES, station.getCargoBundleID());
for(int i = 0; i < spaceAvailable.size(); i++){
int space = spaceAvailable.get(i);
int atStation = cb.getAmount(i);
if(space * atStation > 0){
logger.fine("There is cargo to transfer!");
return true;
}
}
return !ta.keepWaiting();
}
return hasFinishedLastActivity;
}

testBuyingStakesInOtherRRs

Class: jfreerails.controller.FinancialDataGathererTest

Documentation

No documentation available

Source Code

public void testBuyingStakesInOtherRRs(){
w = new WorldImpl();
Player[] players = new Player[2];
for(int i = 0; i < players.length; i++){
players[i] = new Player("Player "+i, i);
Move addPlayer = AddPlayerMove.generateMove(w, players[i]);
MoveStatus ms = addPlayer.doMove(w, Player.AUTHORITATIVE);
assertTrue(ms.ok);
}
//Make player #0 buy stock in player #1
int quantity = 10000;
Transaction t = StockTransaction.buyOrSellStock(1, quantity, new Money(5));
w.addTransaction(players[0].getPrincipal(), t);
FinancialDataGatherer fdg = new FinancialDataGatherer(w, players[0].getPrincipal());
assertEquals(0, fdg.treasuryStock());
int actual = fdg.getStockInRRs()[1];
assertEquals(quantity, actual);
}

generateWorld

Class: jfreerails.server.MapFixtureFactory2

Documentation

No documentation available

Source Code

private static World generateWorld() {
World world = new WorldImpl(50, 50);
TileSetFactory tileFactory = new TileSetFactoryImpl();
WagonAndEngineTypesFactory wetf = new WagonAndEngineTypesFactory();
wetf.addTypesToWorld(world);
tileFactory.addTerrainTileTypesList(world);
URL track_xml_url = OldWorldImpl.class
.getResource("/jfreerails/data/track_tiles.xml");
Track_TilesHandlerImpl trackSetFactory = new Track_TilesHandlerImpl(
track_xml_url);
trackSetFactory.addTrackRules(world);
// Add 4 players
for (int i = 0; i < 4; i++) {
String name = "player" + i;
Player p = new Player(name, i);
AddPlayerMove move = AddPlayerMove.generateMove(world, p);
MoveStatus ms = move.doMove(world, Player.AUTHORITATIVE);
assert(ms.ok);
}
world.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
world.setTime(new GameTime(0));
world.set(ITEM.GAME_SPEED, new GameSpeed(10));
world.set(ITEM.GAME_RULES, GameRules.DEFAULT_RULES);
int clearTypeID = 0;
// Fill the world with clear terrain.
for (int i = 0; i < world.size(SKEY.TERRAIN_TYPES); i++) {
TerrainType tt = (TerrainType) world.get(SKEY.TERRAIN_TYPES, i);
if ("Clear".equals(tt.getTerrainTypeName())) {
clearTypeID = i;
break;
}
}
FreerailsTile tile = FreerailsTile.getInstance(clearTypeID);
for (int x = 0; x < world.getMapWidth(); x++) {
for (int y = 0; y < world.getMapHeight(); y++) {
world.setTile(x, y, tile);
}
}
return world;
}

getStationRadius

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

public int getStationRadius() {
return 0;
}

Called Methods

No outgoing method calls

getStationOfOrigin

Class: jfreerails.world.cargo.CargoBatch

Documentation

No documentation available

Source Code

public int getStationOfOrigin() {
return stationOfOrigin;
}

Called Methods

No outgoing method calls

setupWorld

Class: jfreerails.controller.AddTrainPreMoveTest

Documentation

No documentation available

Source Code

@Override
protected void setupWorld() {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
trackBuilder = new TrackMoveProducer(me, world, mr);
stationBuilder = new StationBuilder(me);
// Build track.
stationBuilder
.setStationType(stationBuilder.getTrackTypeID("terminal"));
Step[] track = {EAST, EAST, EAST, EAST, EAST, EAST, EAST, EAST, EAST};
stationA = new ImPoint(10, 10);
MoveStatus ms0 = trackBuilder.buildTrack(stationA, track);
assertTrue(ms0.ok);
// Build 2 stations.
MoveStatus ms1 = stationBuilder.buildStation(stationA);
assertTrue(ms1.ok);
stationB = new ImPoint(19, 10);
MoveStatus ms2 = stationBuilder.buildStation(stationB);
assertTrue(ms2.ok);
TrainOrdersModel order0 = new TrainOrdersModel(0, null, false, false);
TrainOrdersModel order1 = new TrainOrdersModel(1, null, false, false);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
defaultSchedule = s.toImmutableSchedule();
}

isSuccessful

Class: jfreerails.network.specifics.LogOnResponse

Documentation

No documentation available

Source Code

public boolean isSuccessful() {
return successful;
}

Called Methods

No outgoing method calls

clearStackIfStale

Class: jfreerails.controller.TrackMoveProducer

Documentation

/**
* Moves are only un-doable if no game time has passed since they they were
* executed. This method clears the move stack if the moves were added to
* the stack at a time other than the current time.
*/

Source Code

/**
* Moves are only un-doable if no game time has passed since they they were
* executed. This method clears the move stack if the moves were added to
* the stack at a time other than the current time.
*/
private void clearStackIfStale() {
ReadOnlyWorld w = executor.getWorld();
GameTime currentTime = w.currentTime();
if (!currentTime.equals(lastMoveTime)) {
moveStack.clear();
lastMoveTime = currentTime;
}
}

InetConnection

Class: jfreerails.network.InetConnection

Documentation

No documentation available

Source Code

InetConnection(String s, int port) throws IOException {
this(new Socket(s, port));
}

hashCode

Class: jfreerails.move.ChangeTileMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = x;
result = 29 * result + y;
result = 29 * result + before.hashCode();
result = 29 * result + after.hashCode();
return result;
}

removeLastPlayer

Class: jfreerails.world.top.WorldImpl

Documentation

/**
* Removes the last player to be added.
*
* @return the player that was removed.
* @throws IllegalStateException
* if any elements belonging to the player have not been
* removed.
*/

Source Code

/**
* Removes the last player to be added.
*
* @return the player that was removed.
* @throws IllegalStateException
* if any elements belonging to the player have not been
* removed.
*/
public Player removeLastPlayer() {
int playerID = bankAccounts.removeLastD1();
while (lists.sizeD2(playerID) > 0)
lists.removeLastD2(playerID);
lists.removeLastD1();
currentBalance.removeLast();
activityLists.removeLastD1();
return players.removeLast();
}

test1

Class: jfreerails.controller.BuildTrackExplorerTest

Documentation

/**
* On a blank map, we should be able to build track in any direction as long
* as it does not go off the map.
*/

Source Code

/**
* On a blank map, we should be able to build track in any direction as long
* as it does not go off the map.
*/
public void test1() {
PositionOnTrack start;
// Test starting in the middle of the map.
start = PositionOnTrack.createComingFrom(10, 10, Step.NORTH);
BuildTrackExplorer explorer = new BuildTrackExplorer(world, principal);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.NORTH, 10, 9, explorer);
assertNextVertexIs(Step.NORTH_EAST, 11, 9, explorer);
assertNextVertexIs(Step.EAST, 11, 10, explorer);
// We miss out SW, S, and SE since we don't want to double back on
// ourselves.
assertNextVertexIs(Step.WEST, 9, 10, explorer);
assertNextVertexIs(Step.NORTH_WEST, 9, 9, explorer);
assertFalse(explorer.hasNextEdge());
// Test starting in the top left of the map.
start = PositionOnTrack.createComingFrom(0, 0, Step.SOUTH_EAST);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.EAST, 1, 0, explorer);
assertNextVertexIs(Step.SOUTH_EAST, 1, 1, explorer);
assertNextVertexIs(Step.SOUTH, 0, 1, explorer);
assertFalse(explorer.hasNextEdge());
// Test starting in the bottom right of the map.
start = PositionOnTrack.createComingFrom(19, 19, Step.NORTH_WEST);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.NORTH, 19, 18, explorer);
assertNextVertexIs(Step.WEST, 18, 19, explorer);
assertNextVertexIs(Step.NORTH_WEST, 18, 18, explorer);
assertFalse(explorer.hasNextEdge());
}

initComponents

Class: jfreerails.client.view.SelectStationJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
cargoWaitingAndDemandedJPanel1 = new jfreerails.client.view.CargoWaitingAndDemandedJPanel();
jLabel1 = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(500, 350));
addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
@Override
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
formMouseClicked(evt);
}
});
addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
@Override
public void mouseMoved(java.awt.event.MouseEvent evt) {
formMouseMoved(evt);
}
});
cargoWaitingAndDemandedJPanel1
.setBorder(new javax.swing.border.LineBorder(
new java.awt.Color(0, 0, 0)));
cargoWaitingAndDemandedJPanel1.setPreferredSize(new java.awt.Dimension(
165, 300));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(cargoWaitingAndDemandedJPanel1, gridBagConstraints);
jLabel1.setText("Train #1 Stop 1");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
gridBagConstraints.weightx = 1.0;
add(jLabel1, gridBagConstraints);
}// GEN-END:initComponents

addD1

Class: jfreerails.util.List2D

Documentation

No documentation available

Source Code

int addD1();

Called Methods

No outgoing method calls

generateMove

Class: jfreerails.move.TransferCargoAtStationMove

Documentation

No documentation available

Source Code

public static TransferCargoAtStationMove generateMove(
ChangeCargoBundleMove changeAtStation,
ChangeCargoBundleMove changeOnTrain, CompositeMove payment,
boolean waiting) {
return new TransferCargoAtStationMove(new Move[] { changeAtStation,
changeOnTrain, payment }, waiting);
}

Called Methods

No outgoing method calls

usedEntries

Class: jfreerails.util.LRUCache

Documentation

/**
* Returns the number of used entries in the cache.
*
* @return the number of entries currently in the cache.
*/

Source Code

/**
* Returns the number of used entries in the cache.
*
* @return the number of entries currently in the cache.
*/
public synchronized int usedEntries() {
return map.size();
}

Called Methods

No outgoing method calls

readResolve

Class: jfreerails.controller.PreMoveStatus

Documentation

/**
* Avoid creating a duplicate when deserializing.
*/

Source Code

/**
* Avoid creating a duplicate when deserializing.
*/
private Object readResolve() {
if (ms.ok) {
return PRE_MOVE_OK;
}
return this;
}

Called Methods

No outgoing method calls

testSetIntIntT

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List2DDiff.set(int, int, T)'
*/
public void testSetIntIntT() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
assertEquals(String.valueOf(2), diffs.get(0, 1));
diffs.set(0, 1, String.valueOf(22));
assertEquals(String.valueOf(22), diffs.get(0, 1));
diffs.addD2(0, String.valueOf(3));
assertEquals(String.valueOf(3), diffs.get(0, 2));
diffs.set(0, 2, String.valueOf(33));
assertEquals(String.valueOf(33), diffs.get(0, 2));
}

paint

Class: jfreerails.client.view.NewsPaperJPanel

Documentation

No documentation available

Source Code

// GEN-LAST:event_formKeyPressed
@Override
public void paint(Graphics g) {
g.drawImage(this.pieceOfNewspaper, 0, 0, null);
this.paintChildren(g);
}

Called Methods

No outgoing method calls

generateMove

Class: jfreerails.controller.PreMove

Documentation

No documentation available

Source Code

Move generateMove(ReadOnlyWorld w);

Called Methods

No outgoing method calls

hasPriorityOrders

Class: jfreerails.world.train.ImmutableSchedule

Documentation

No documentation available

Source Code

public boolean hasPriorityOrders() {
return hasPriorityOrders;
}

Called Methods

No outgoing method calls

getStationBuildAction

Class: jfreerails.client.view.StationBuildModel

Documentation

No documentation available

Source Code

public StationBuildAction getStationBuildAction() {
return stationBuildAction;
}

Called Methods

No outgoing method calls

dumpImages

Class: jfreerails.client.renderer.AbstractTileRenderer

Documentation

No documentation available

Source Code

abstract public void dumpImages(ImageManager imageManager);

Called Methods

No outgoing method calls

getLegalConfigurationsIterator

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

public Iterator<TrackConfiguration> getLegalConfigurationsIterator() {
return legalConfigurations.getLegalConfigurationsIterator();
}

setSelected

Class: jfreerails.client.common.MappedButtonModel

Documentation

No documentation available

Source Code

@Override
public void setSelected(boolean b) {
if (isSelected() != b) {
super.setSelected(b);
if (b) {
ActionAdapter.this.setSelectedItem(actionName);
}
}
}

listUpdated

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

public void listUpdated(KEY key, int index, FreerailsPrincipal p) {
if (KEY.TRAIN_SCHEDULES == key && this.scheduleID == index) {
listModel.fireRefresh();
enableButtons();
}
}

hashCode

Class: jfreerails.move.AddActiveEntityMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = activity.hashCode();
result = 29 * result + principal.hashCode();
result = 29 * result + index;
return result;
}

Called Methods

No outgoing method calls

get

Class: jfreerails.world.common.ImStringList

Documentation

No documentation available

Source Code

public String get(int i) {
return strings[i];
}

Called Methods

No outgoing method calls

addTerrainTileTypesList

Class: jfreerails.server.common.TileSetFactory

Documentation

No documentation available

Source Code

void addTerrainTileTypesList(World w);

Called Methods

No outgoing method calls

advanceTimeOneYear

Class: jfreerails.controller.StockPriceCalculatorTest

Documentation

No documentation available

Source Code

private void advanceTimeOneYear() {
GameCalendar calendar = (GameCalendar) w.get(ITEM.CALENDAR);
int tpy = calendar.getTicksPerYear();
int currentTicks = w.currentTime().getTicks();
GameTime newTime = new GameTime(currentTicks + tpy);
w.setTime(newTime);
}

paintRectangleOfTiles

Class: jfreerails.client.renderer.MapBackgroundRender

Documentation

No documentation available

Source Code

private void paintRectangleOfTiles(Graphics g, int x, int y, int width,
int height) {
terrainLayer.paintRectangleOfTiles(g, x, y, width, height);
trackLayer.paintRectangleOfTiles(g, x, y, width, height);
cityNames.paint((Graphics2D) g);
stationNames.paint((Graphics2D) g);
}

Called Methods

  • jfreerails.client.common.Painter.paint
  • jfreerails.client.renderer.MapBackgroundRender.TerrainLayer.paintRectangleOfTiles (external)
  • jfreerails.client.renderer.MapBackgroundRender.TrackLayer.paintRectangleOfTiles (external)

BrokerJFrame

Class: jfreerails.client.view.BrokerJFrame

Documentation

No documentation available

Source Code

public BrokerJFrame(URL url, HashMap context) {
initComponents();
String template = loadText(url);
String populatedTemplate = populateTokens(template, context);
setHtml(populatedTemplate);
}

DropOffAndPickupCargoMoveGenerator

Class: jfreerails.controller.DropOffAndPickupCargoMoveGenerator

Documentation

/**
* Constructor.
*
* @param trainNo
* ID of the train
* @param stationNo
* ID of the station
* @param world
* The world object
*/

Source Code

/**
* Constructor.
*
* @param trainNo
* ID of the train
* @param stationNo
* ID of the station
* @param world
* The world object
*/
public DropOffAndPickupCargoMoveGenerator(int trainNo, int stationNo, ReadOnlyWorld world,
FreerailsPrincipal p, boolean waiting, boolean autoConsist) {
principal = p;
trainId = trainNo;
stationId = stationNo;
w = world;
this.autoConsist = autoConsist;
this.waitingForFullLoad = waiting;
train = new TrainAccessor(w, principal, trainNo);
consist = train.getTrain().getConsist();
getBundles();
processTrainBundle(); // ie. unload train / dropoff cargo
if (autoConsist) {
ArrayList<WagonLoad> wagonsAvailable = new ArrayList<WagonLoad>();
assert (train.equals(world.get(principal, KEY.TRAINS, this.trainId)));
Schedule schedule = train.getSchedule();
TrainOrdersModel order = schedule.getOrder(schedule.getOrderToGoto());
int nextStationId = order.stationId;
StationModel stationModel = (StationModel) w
.get(principal, KEY.STATIONS, nextStationId);
Demand4Cargo demand = stationModel.getDemand();
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
// If this cargo is demanded at the next scheduled station.
if (demand.isCargoDemanded(i)) {
int amount = stationAfter.getAmount(i);
while (amount > 0) {
int amount2remove = Math.min(amount, WagonType.UNITS_OF_CARGO_PER_WAGON);
amount -= amount2remove;
// Don't bother with less than half a wagon load.
if (amount2remove * 2 > WagonType.UNITS_OF_CARGO_PER_WAGON) {
wagonsAvailable.add(new WagonLoad(amount2remove, i));
}
}
}
}
Collections.sort(wagonsAvailable);
int numWagons2add = Math.min(wagonsAvailable.size(), 3);
int[] temp = new int[numWagons2add];
for (int i = 0; i < numWagons2add; i++) {
WagonLoad wagonload = wagonsAvailable.get(i);
temp[i] = wagonload.cargoType;
}
consist = new ImInts(temp);
}
processStationBundle(); // ie. load train / pickup cargo
}

paintComponent

Class: jfreerails.client.view.MapViewJComponent

Documentation

No documentation available

Source Code

@Override
protected void paintComponent(java.awt.Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
java.awt.Rectangle r = this.getVisibleRect();
getMapView().paintRect(g2, r);
}

loadTrackViews

Class: jfreerails.client.top.RenderersRootImpl

Documentation

No documentation available

Source Code

private TrackPieceRendererList loadTrackViews(ReadOnlyWorld w,
FreerailsProgressMonitor pm) throws IOException {
return new TrackPieceRendererList(w, imageManager, pm);
}

Called Methods

No outgoing method calls

itemRemoved

Class: jfreerails.client.view.TrainListCellRenderer

Documentation

No documentation available

Source Code

public void itemRemoved(KEY key, int index, FreerailsPrincipal p) {
}

Called Methods

No outgoing method calls

itemRemoved

Class: jfreerails.client.view.StationInfoJPanel

Documentation

No documentation available

Source Code

public void itemRemoved(KEY key, int index, FreerailsPrincipal principal) {
if (modelRoot.getPrincipal().equals(principal))
reactToUpdate(key, index, false);
}

loadSession

Class: jfreerails.world.player.Player

Documentation

/**
* Called by the client to reconstitute the data from a saved game.
*/

Source Code

/**
* Called by the client to reconstitute the data from a saved game.
*/
public void loadSession(ObjectInputStream in) throws IOException {
// try {
// privateData = (PrivateData) in.readObject();
// } catch (ClassNotFoundException e) {
// throw new IOException("Couldn't find class:" + e);
// }
}

Called Methods

No outgoing method calls

getID

Class: jfreerails.network.specifics.SetWorldMessage2Client

Documentation

No documentation available

Source Code

public int getID() {
return id;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return 666;
}

Called Methods

No outgoing method calls

paintRect

Class: jfreerails.client.renderer.TrackLayer

Documentation

No documentation available

Source Code

public void paintRect(Graphics g, Rectangle visibleRect) {
throw new UnsupportedOperationException(
"Method not yet implemented.");
}

Called Methods

No outgoing method calls

generateMove

Class: jfreerails.move.AddStationMove

Documentation

No documentation available

Source Code

public static AddStationMove generateMove(ReadOnlyWorld w,
String stationName, ImPoint p,
ChangeTrackPieceMove upgradeTrackMove, FreerailsPrincipal principal) {
int cargoBundleNumber = w.size(principal, KEY.CARGO_BUNDLES);
Move addCargoBundleMove = new AddCargoBundleMove(cargoBundleNumber,
ImmutableCargoBundle.EMPTY_BUNDLE, principal);
int stationNumber = w.size(principal, KEY.STATIONS);
StationModel station = new StationModel(p.x, p.y, stationName, w
.size(SKEY.CARGO_TYPES), cargoBundleNumber);
Move addStation = new AddItemToListMove(KEY.STATIONS, stationNumber,
station, principal);
return new AddStationMove(new Move[] { upgradeTrackMove,
addCargoBundleMove, addStation });
}

clientUpdates

Class: jfreerails.launcher.GUIClient

Documentation

No documentation available

Source Code

@Override
protected void clientUpdates() {
if (factory.isSetup()) {
factory.getBuildTrackController().update();
// Update sub tick time.
long currentTime = System.currentTimeMillis();
long lastTick = getLastTickTime();
double dt = currentTime - lastTick;
ReadOnlyWorld world2 = modelRoot.getWorld();
GameSpeed gameSpeed = (GameSpeed) world2.get(ITEM.GAME_SPEED);
GameTime currentGameTime = world2.currentTime();
double ticks = currentGameTime.getTicks();
if(!gameSpeed.isPaused()){
double milliSecondsPerTick = 1000/ gameSpeed.getSpeed();
double subTicks = dt / milliSecondsPerTick;
subTicks = Math.min(dt, 1d);
ticks += subTicks;
}
modelRoot.setProperty(Property.TIME, new Double(ticks));
}
}

setup

Class: jfreerails.client.view.DateJLabel

Documentation

No documentation available

Source Code

public void setup(ModelRoot model, RenderersRoot vl,
Action closeAction) {
this.w = model.getWorld();
}

createGameMenu

Class: experimental.SimpleComponentFactoryImpl2

Documentation

No documentation available

Source Code

public JMenu createGameMenu() {
return new JMenu("Game");
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.player.PlayerPrincipal

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return id;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.move.MapDiff

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof MapDiff))
return false;
final MapDiff diff = (MapDiff) o;
if (x != diff.x)
return false;
if (y != diff.y)
return false;
if (!after.equals(diff.after))
return false;
if (!before.equals(diff.before))
return false;
return true;
}

Called Methods

No outgoing method calls

hide

Class: jfreerails.client.renderer.BuildTrackController

Documentation

/** Hides and cancels any proposed track. */

Source Code

/** Hides and cancels any proposed track. */
public void hide() {
this.setVisible(false);
setTargetPoint(null);
reset();
}

get

Class: jfreerails.util.List1DImpl

Documentation

No documentation available

Source Code

public T get(int i) {
return elementData.get(i);
}

Called Methods

No outgoing method calls

hasNext

Class: jfreerails.world.train.SimplePathIteratorImpl

Documentation

No documentation available

Source Code

public boolean hasNext() {
return (position + 1) < x.size();
}

getRuleList

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public List<TrackRule> getRuleList() {
return ruleList;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.train.PathOnTiles

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof PathOnTiles))
return false;
final PathOnTiles pathOnTiles = (PathOnTiles) o;
if (!start.equals(pathOnTiles.start))
return false;
if (!vectors.equals(pathOnTiles.vectors))
return false;
return true;
}

getTimeOfDay

Class: jfreerails.world.common.GameCalendar

Documentation

/**
* Returns the time of day as a string, note that a year is made up of a
* representative day, so 1st June is equivalent to 12 noon.
*/

Source Code

/**
* Returns the time of day as a string, note that a year is made up of a
* representative day, so 1st June is equivalent to 12 noon.
*/
public String getTimeOfDay(int i) {
int ticksPerHour = ticksPerYear / 24;
int hour = ticksPerHour == 0 ? 0 : (i % ticksPerYear) / ticksPerHour;
int ticksPerMinute = ticksPerYear / (24 * 60);
int minute = ticksPerMinute == 0 ? 0 : (i % (ticksPerMinute * 60));
return decimalFormat.format(hour) + ":" + decimalFormat.format(minute);
}

Called Methods

No outgoing method calls

readResolve

Class: jfreerails.world.track.FreerailsTile

Documentation

No documentation available

Source Code

private Object readResolve() throws ObjectStreamException {
if (instances.containsKey(this)) {
return instances.get(this);
}
instances.put(this, this);
return this;
}

Called Methods

No outgoing method calls

topSpeed

Class: jfreerails.controller.MoveTrainPreMove

Documentation

No documentation available

Source Code

double topSpeed(int wagons) {
return 10 / (wagons + 1);
}

Called Methods

No outgoing method calls

testSmallestF

Class: jfreerails.controller.OpenListTest

Documentation

No documentation available

Source Code

public void testSmallestF() {
OpenList openList = new OpenList();
openList.add(0, 4);
assertEquals(4, openList.smallestF());
openList.add(1, 5);
assertEquals(4, openList.smallestF());
openList.add(5, 1);
assertEquals(1, openList.smallestF());
openList.popNodeWithSmallestF();
assertEquals(4, openList.smallestF());
openList.popNodeWithSmallestF();
assertEquals(5, openList.smallestF());
}

getImage

Class: jfreerails.client.renderer.RenderersRoot

Documentation

No documentation available

Source Code

Image getImage(String relativeFilename) throws IOException;

Called Methods

No outgoing method calls

get

Class: jfreerails.util.LRUCache

Documentation

/**
* Retrieves an entry from the cache.<br>
* The retrieved entry becomes the MRU (most recently used) entry.
*
* @param key
* the key whose associated value is to be returned.
* @return the value associated to this key, or null if no value with this
* key exists in the cache.
*/

Source Code

/**
* Retrieves an entry from the cache.<br>
* The retrieved entry becomes the MRU (most recently used) entry.
*
* @param key
* the key whose associated value is to be returned.
* @return the value associated to this key, or null if no value with this
* key exists in the cache.
*/
public synchronized V get(K key) {
return map.get(key);
}

Called Methods

No outgoing method calls

rollBackPrecommittedMoves

Class: jfreerails.network.specifics.MovePrecommitter

Documentation

/**
* Undoes each of the precommitted moves and puts them back on the
* uncommitted list.
*/

Source Code

/**
* Undoes each of the precommitted moves and puts them back on the
* uncommitted list.
*/
private void rollBackPrecommittedMoves() {
while (precomitted.size() > 0) {
Object last = precomitted.removeLast();
Move move2undo;
FreerailsSerializable obj2add2uncomitted;
if (last instanceof Move) {
move2undo = (Move) last;
obj2add2uncomitted = move2undo;
} else if (last instanceof PreMoveAndMove) {
PreMoveAndMove pmam = (PreMoveAndMove) last;
move2undo = pmam.m;
obj2add2uncomitted = pmam.pm;
} else {
throw new IllegalStateException();
}
MoveStatus ms = move2undo.undoMove(w, Player.AUTHORITATIVE);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
uncomitted.addFirst(obj2add2uncomitted);
}
}

getCategory

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

public TrackRule.TrackCategories getCategory() {
return properties.getCategory();
}

testNextSpeeds

Class: jfreerails.controller.MoveTrainPreMove1stTest

Documentation

No documentation available

Source Code

public void testNextSpeeds() {
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
SpeedAgainstTime speeds = preMove.nextSpeeds(world, EAST);
assertNotNull(speeds);
assertEquals(speeds.calcV(0), 0d);
assertTrue(speeds.getS() >= EAST.getLength());
double t = speeds.getT();
assertTrue(t > 0);
assertTrue(speeds.calcV(t) > 0);
}

addConnection

Class: jfreerails.network.EchoGameServer

Documentation

No documentation available

Source Code

public synchronized void addConnection(Connection2Client connection) {
if (null == connection) {
throw new NullPointerException();
}
if (!status.isOpen()) {
throw new IllegalArgumentException();
}
connections.add(connection);
}

hasPriorityOrders

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public boolean hasPriorityOrders() {
return this.hasPriorityOrders;
}

Called Methods

No outgoing method calls

testBondsFigure

Class: jfreerails.client.view.BalanceSheetGeneratorTest

Documentation

No documentation available

Source Code

public void testBondsFigure() {
BalanceSheetGenerator generator = new BalanceSheetGenerator(world,
player.getPrincipal());
Money expectedBondValue = new Money(BondTransaction.BOND_VALUE_ISSUE
.getAmount());
assertEquals(expectedBondValue.changeSign(), generator.total.loans);
assertEquals(expectedBondValue.changeSign(), generator.ytd.loans);
}

testUGet

Class: jfreerails.util.List3DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List3DDiff.uGet(int...)'
*/
public void testUGet() {
underlying.addD1();
underlying.addD2(0);
underlying.addD3(0,0, new Integer(1));
assertEquals(new Integer(1), diffs.uGet(0,0,0));
}

equals

Class: jfreerails.world.station.ConvertedAtStation

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof ConvertedAtStation) {
ConvertedAtStation test = (ConvertedAtStation) o;
if (this.convertedTo.size() != test.convertedTo.size()) {
return false;
}
for (int i = 0; i < convertedTo.size(); i++) {
if (convertedTo.get(i) != test.convertedTo.get(i)) {
return false;
}
}
return true;
}
return false;
}

get

Class: jfreerails.util.List2D

Documentation

No documentation available

Source Code

T get(int d1, int d2);

Called Methods

No outgoing method calls

paintTile

Class: jfreerails.client.renderer.ZoomedOutMapRenderer

Documentation

No documentation available

Source Code

public void paintTile(Graphics g, int tileX, int tileY) {
g.drawImage(mapImage, 0, 0, null);
}

Called Methods

No outgoing method calls

nextSegment

Class: jfreerails.world.common.FreerailsPathIterator

Documentation

/**
* Gets the next segment of the path and places its coordinates in the
* specified IntLine; then moves the iterator forwards by one path segment.
* (The coordinates are placed the passed-in IntLine rather than a new
* object to avoid the cost of object creation.)
*
* @param line
*/

Source Code

/**
* Gets the next segment of the path and places its coordinates in the
* specified IntLine; then moves the iterator forwards by one path segment.
* (The coordinates are placed the passed-in IntLine rather than a new
* object to avoid the cost of object creation.)
*
* @param line
*/
void nextSegment(IntLine line);

Called Methods

No outgoing method calls

toString

Class: jfreerails.world.common.GameTime

Documentation

No documentation available

Source Code

@Override
public String toString() {
return "GameTime:" + String.valueOf(ticks);
}

Called Methods

No outgoing method calls

AddItemTransaction

Class: jfreerails.world.accounts.AddItemTransaction

Documentation

No documentation available

Source Code

public AddItemTransaction(Category category, int type, int quantity,
Money amount) {
this.category = category;
this.type = type;
this.quantity = quantity;
this.amount = amount;
}

Called Methods

No outgoing method calls

start_CanOnlyBuildOnTheseTerrainTypes

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void start_CanOnlyBuildOnTheseTerrainTypes(final Attributes meta)
throws SAXException {
terrainTypes = new HashSet<TerrainType.Category>();
}

Called Methods

No outgoing method calls

testLoadingGame

Class: jfreerails.network.specifics.FreerailsClientWithLocalServerTest

Documentation

No documentation available

Source Code

public void testLoadingGame() {
try {
int commandID = 0;
// Add client to server.
FreerailsClient client0 = new FreerailsClient();
LogOnResponse response0 = client0.connect(server, "client0",
"password");
assertTrue(response0.isSuccessful());
client0.update();
// Start game
ImStringList mapNames = (ImStringList) client0
.getProperty(ClientProperty.MAPS_AVAILABLE);
Message2Server newGameMessage2 = new NewGameMessage2Server(
commandID++, mapNames.get(0));
MessageStatus cm = newGameMessage2.execute(server);
assertTrue(cm.isSuccessful());
// Save game and stop server
String savedGameName = "game1";
Message2Server saveGameMessage2 = new SaveGameMessage2Server(
commandID++, savedGameName);
cm = saveGameMessage2.execute(server);
assertTrue(cm.isSuccessful());
server.stopGame();
// Start 2nd server with saved game
server = new FreerailsGameServer(savedGamesManager);
server.loadgame(savedGameName);
assertEquals(0, server.countOpenConnections());
// Attempt to attach invalid player.
client0 = new FreerailsClient();
response0 = client0.connect(server, "client0", "batman");
assertFalse("bad password", response0.isSuccessful());
assertEquals(0, server.countOpenConnections());
response0 = client0.connect(server, "client1", "password");
assertFalse("bad username", response0.isSuccessful());
assertEquals(0, server.countOpenConnections());
response0 = client0.connect(server, "client0", "password");
assertTrue("Ok, same username and password as before.", response0
.isSuccessful());
assertEquals(1, server.countOpenConnections());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}

LegalTrackConfigurations

Class: jfreerails.world.track.LegalTrackConfigurations

Documentation

No documentation available

Source Code

public LegalTrackConfigurations(int max,
ArrayList<String> legalTrackTemplatesArrayList) {
maximumConsecutivePieces = max;
HashSet<TrackConfiguration> temp = new HashSet<TrackConfiguration>();
// Iterate over the track templates.
for (int i = 0; i < legalTrackTemplatesArrayList.size(); i++) {
String trackTemplateString = legalTrackTemplatesArrayList.get(i);
processTemplate(trackTemplateString, temp);
}
legalConfigs = new ImHashSet<TrackConfiguration>(temp);
}

getColor

Class: jfreerails.client.view.PlayerColors

Documentation

No documentation available

Source Code

public static Color getColor(int playerNumber) {
return colors[playerNumber % colors.length];
}

Called Methods

No outgoing method calls

getLegalTrackPlacement

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

public LegalTrackPlacement getLegalTrackPlacement() {
return legalTrackPlacement;
}

Called Methods

No outgoing method calls

getInstance

Class: jfreerails.move.RemoveTrainMove

Documentation

No documentation available

Source Code

public static RemoveTrainMove getInstance(int index, FreerailsPrincipal p,
ReadOnlyWorld world) {
TrainModel train = (TrainModel) world.get(p, KEY.TRAINS, index);
int scheduleId = train.getScheduleID();
ImmutableSchedule schedule = (ImmutableSchedule) world.get(
p, KEY.TRAIN_SCHEDULES, scheduleId);
int cargoBundleId = train.getCargoBundleID();
ImmutableCargoBundle cargoBundle = (ImmutableCargoBundle) world.get(
p, KEY.CARGO_BUNDLES, cargoBundleId);
// TrainPositionOnMap position =
// (TrainPositionOnMap)world.get(KEY.TRAIN_POSITIONS, index, p);
Move removeTrain = new RemoveItemFromListMove(KEY.TRAINS, index, train,
p);
Move removeCargobundle = new RemoveItemFromListMove(KEY.CARGO_BUNDLES,
cargoBundleId, cargoBundle, p);
Move removeSchedule = new RemoveItemFromListMove(KEY.TRAIN_SCHEDULES,
scheduleId, schedule, p);
// Move removePosition = new RemoveItemFromListMove(KEY.TRAIN_POSITIONS,
// index, position, p);
return new RemoveTrainMove(new Move[] { removeTrain, removeCargobundle,
removeSchedule /* , removePosition */
});
}

getClassNameFrom

Class: jfreerails.util.ClassPath

Documentation

/**
* replace ANY slashes with dots and remove the .class at the end of the
* file name.
*
* @param entryName
* a file name relative to the classpath. A class of package org
* found in directory bin would be passed into this method as
* "org/MyClass.class"
* @return a fully qualified Class name.
*/

Source Code

/**
* replace ANY slashes with dots and remove the .class at the end of the
* file name.
*
* @param entryName
* a file name relative to the classpath. A class of package org
* found in directory bin would be passed into this method as
* "org/MyClass.class"
* @return a fully qualified Class name.
*/
private String getClassNameFrom(String entryName) {
String foo = entryName.replace('/', '.');
foo = foo.replace('\\', '.');
return foo.substring(0, foo.lastIndexOf('.'));
}

Called Methods

No outgoing method calls

jList1ValueChanged

Class: jfreerails.launcher.ClientOptionsJPanel

Documentation

No documentation available

Source Code

private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {// GEN-FIRST:event_jList1ValueChanged
validateInput();
}// GEN-LAST:event_jList1ValueChanged

refreshTile

Class: jfreerails.client.renderer.MapBackgroundRender

Documentation

No documentation available

Source Code

public void refreshTile(int x, int y) {
// Do nothing
}

Called Methods

No outgoing method calls

newGame

Class: jfreerails.controller.ServerControlInterface

Documentation

No documentation available

Source Code

void newGame(String mapName);

Called Methods

No outgoing method calls

getPlayerID

Class: jfreerails.network.specifics.LogOnResponse

Documentation

No documentation available

Source Code

public int getPlayerID() {
return playerNumber;
}

Called Methods

No outgoing method calls

contains

Class: jfreerails.world.cargo.CargoBundle

Documentation

No documentation available

Source Code

boolean contains(CargoBatch cb);

Called Methods

No outgoing method calls

testMove

Class: jfreerails.move.MapDiffMoveTest

Documentation

No documentation available

Source Code

@Override
public void testMove() {
World world2 = this.getWorld();
WorldDiffs worldDiff = new WorldDiffs(world2);
FreerailsTile tile = (FreerailsTile) world2.getTile(2, 2);
assertNotNull(tile);
assertEquals(tile, worldDiff.getTile(2, 2));
FreerailsTile newTile = FreerailsTile.getInstance(999);
worldDiff.setTile(3, 5, newTile);
assertEquals(newTile, worldDiff.getTile(3, 5));
Move m = new WorldDiffMove(world2, worldDiff, WorldDiffMove.Cause.Other);
this.assertDoMoveIsOk(m);
this.assertUndoMoveIsOk(m);
this.assertDoThenUndoLeavesWorldUnchanged(m);
this.assertSurvivesSerialisation(m);
}

compositeTest

Class: jfreerails.move.ChangeTrackPieceCompositeMove

Documentation

No documentation available

Source Code

@Override
protected MoveStatus compositeTest(World world, FreerailsPrincipal p) {
if (mustConnectToExistingTrack(world)) {
if (hasAnyTrackBeenBuilt(world, this.builder)) {
try {
ChangeTrackPieceMove a = (ChangeTrackPieceMove) super
.getMove(0);
ChangeTrackPieceMove b = (ChangeTrackPieceMove) super
.getMove(1);
int ruleBeforeA = a.trackPieceBefore.getTrackTypeID();
int ruleBeforeB = b.trackPieceBefore.getTrackTypeID();
if (ruleBeforeA == NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER
&& ruleBeforeB == NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
return MoveStatus
.moveFailed("Must connect to existing track");
}
} catch (ClassCastException e) {
// It was not the type of move we expected.
// We end up here when we are removing a station.
return MoveStatus.MOVE_OK;
}
}
}
return MoveStatus.MOVE_OK;
}

getCurrentBalance

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

No documentation available

Source Code

Money getCurrentBalance(FreerailsPrincipal p);

Called Methods

No outgoing method calls

Categories

Class: jfreerails.world.cargo.Categories

Documentation

No documentation available

Source Code

private Categories(int nr) {
this.nr = nr;
}

Called Methods

No outgoing method calls

clientUpdates

Class: jfreerails.network.specifics.FreerailsClient

Documentation

/**
* Empty method called by update(), subclasses should override this method
* instead of overriding update().
*
*/

Source Code

/**
* Empty method called by update(), subclasses should override this method
* instead of overriding update().
*
*/
protected void clientUpdates() {
}

Called Methods

No outgoing method calls

testMove

Class: jfreerails.move.AddCargoBundleMoveTest

Documentation

No documentation available

Source Code

@Override
public void testMove() {
MutableCargoBundle bundleA;
MutableCargoBundle bundleB;
bundleA = new MutableCargoBundle();
bundleB = new MutableCargoBundle();
bundleA.setAmount(new CargoBatch(1, 2, 3, 4, 0), 5);
bundleB.setAmount(new CargoBatch(1, 2, 3, 4, 0), 5);
assertEquals(bundleA, bundleB);
Move m = new AddCargoBundleMove(0, bundleA.toImmutableCargoBundle(),
MapFixtureFactory.TEST_PRINCIPAL);
assertDoMoveIsOk(m);
assertEquals(getWorld().size(MapFixtureFactory.TEST_PRINCIPAL,
KEY.CARGO_BUNDLES), 1);
assertUndoMoveIsOk(m);
assertSurvivesSerialisation(m);
assertOkButNotRepeatable(m);
}

testTrainImages

Class: jfreerails.client.renderer.TrainRendererTest

Documentation

No documentation available

Source Code

@Test
public void testTrainImages() {
RenderersRoot rr = new MyRenderersRoot();
TrainImages wagonImages = rr.getWagonImages(0);
assertNotNull(wagonImages);
TrainImages engineImages = rr.getEngineImages(0);
assertNotNull(engineImages);
for (Step step : Step.getList()) {
Image overheadImage = wagonImages.getOverheadImage(step.getID());
assertTrue(overheadImage instanceof BufferedImage);
}
}

genText

Class: jfreerails.controller.ReportBugTextGenerator

Documentation

No documentation available

Source Code

public static String genText() {
StringBuffer sb = new StringBuffer();
sb.append("How to report a bug\n");
sb.append("\n");
sb.append("Use the sourceforge.net bug tracker at the following url:\n");
sb.append(TRACKER_URL);
sb.append("\n");
sb.append("\n");
sb.append("Please include:\n");
sb.append(" 1. Steps to reproduce the bug (attach a save game if appropriate).\n");
sb.append(" 2. What you expected to see.\n");
sb.append(" 3. What you saw instead (attach a screenshot if appropriate).\n");
sb.append(" 4. The details below (copy and past them into the bug report).\n");
appendBuildProps(sb);
sb.append("\n");
sb.append("\n");
return sb.toString();
}

wireUp

Class: jfreerails.client.view.StationPlacementCursor

Documentation

No documentation available

Source Code

public static void wireUp(ActionRoot actionRoot, StationRadiusRenderer srr,
MapViewJComponent mapView) {
StationPlacementCursor spc = new StationPlacementCursor(actionRoot,
srr, mapView);
spc.init();
}

getNewTrackPiece

Class: jfreerails.move.ChangeTrackPieceMove

Documentation

No documentation available

Source Code

public TrackPiece getNewTrackPiece() {
return trackPieceAfter;
}

Called Methods

No outgoing method calls

getAmount

Class: jfreerails.world.cargo.MutableCargoBundle

Documentation

No documentation available

Source Code

public int getAmount(CargoBatch cb) {
if (contains(cb)) {
Integer i = sortedMap.get(cb);
return i.intValue();
}
return 0;
}

getX

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

public int getX() {
return x;
}

Called Methods

No outgoing method calls

processMove

Class: jfreerails.move.TrackMoveTransactionsGenerator

Documentation

No documentation available

Source Code

private void processMove(ChangeTrackPieceMove move) {
TrackPiece newTrackPiece = move.getNewTrackPiece();
TrackRule newTrackRule = newTrackPiece.getTrackRule();
final int ruleAfter = newTrackPiece.getTrackTypeID();
TrackPiece oldTrackPiece = move.getOldTrackPiece();
final int ruleBefore = oldTrackPiece.getTrackTypeID();
final int oldLength = oldTrackPiece.getTrackConfiguration().getLength();
final int newLength = newTrackPiece.getTrackConfiguration().getLength();
if (ruleAfter != ruleBefore) {
TrackRule.TrackCategories category = newTrackRule.getCategory();
switch (category) {
case station: {
fixedCostsStations -= newTrackRule.getFixedCost().getAmount();
break;
}
case bridge: {
fixedCostsBridges -= newTrackRule.getFixedCost().getAmount();
break;
}
default: {
// Do nothing.
}
}
}
if (ruleAfter == ruleBefore) {
if (oldLength < newLength) {
trackAdded[ruleAfter] += (newLength - oldLength);
} else if (oldLength > newLength) {
trackRemoved[ruleAfter] += (oldLength - newLength);
}
return;
}
if (ruleAfter != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
trackAdded[ruleAfter] += newLength;
}
if (ruleBefore != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
trackRemoved[ruleBefore] += oldLength;
}
}

addwagon

Class: jfreerails.client.view.SelectWagonsJPanel

Documentation

No documentation available

Source Code

// Adds the wagon selected in the list to the train consist.
private void addwagon() {
if (wagons.size() < TrainModel.MAX_NUMBER_OF_WAGONS) {
int type = wagonTypesJList.getSelectedIndex();
wagons.add(new Integer(type));
updateMaxWagonsText();
this.repaint();
}
}

initialize

Class: jfreerails.client.view.LeaderBoardJPanel

Documentation

/**
* This method initializes this
*/

Source Code

/**
* This method initializes this
*/
private void initialize() {
this.add(getPlayersList(), null);
java.awt.event.MouseAdapter mouseAdapter = new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
if (null == submitButtonCallBack) {
System.err.println("mouseClicked");
} else {
submitButtonCallBack.actionPerformed(new ActionEvent(
this, 0, null));
}
}
};
this.addMouseListener(mouseAdapter);
this.playersList.addMouseListener(mouseAdapter);
this.setSize(getPreferredSize());
}

searchStatus

Class: jfreerails.client.renderer.BuildTrackController

Documentation

No documentation available

Source Code

int searchStatus() {
if (buildNewTrack) {
return path4newTrackFinder.getStatus();
}
return pathOnExistingTrackFinder.getStatus();
}

getIcon

Class: jfreerails.client.renderer.AbstractTileRenderer

Documentation

/**
* Returns an icon for the tile at x,y, which may depend on the terrain
* types of of the surrounding tiles.
*/

Source Code

/**
* Returns an icon for the tile at x,y, which may depend on the terrain
* types of of the surrounding tiles.
*/
Image getIcon(int x, int y, ReadOnlyWorld w) {
int tile = selectTileIcon(x, y, w);
if (getTileIcons()[tile] != null) {
return getTileIcons()[tile];
}
throw new NullPointerException("Error in TileView.getIcon: icon no. "
+ tile + "==null");
}

display

Class: jfreerails.client.view.TrainListCellRenderer

Documentation

No documentation available

Source Code

private void display(int engine, ImInts wagons){
images = new Image[1 + wagons.size()];
// images[0] = vl.getTrainImages().getSideOnEngineImage(
// train.getEngineType(), height);
String engineFilename = vl.getEngineImages(engine).sideOnFileName;
try {
images[0] = vl.getScaledImage(engineFilename, height);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException(engineFilename);
}
for (int i = 0; i < wagons.size(); i++) {
// images[i + 1] = vl.getTrainImages().getSideOnWagonImage(
// order.consist.get(i), height);
int wagonType = wagons.get(i);
String wagonFilename = vl.getWagonImages(wagonType).sideOnFileName;
try {
images[i + 1] = vl.getScaledImage(wagonFilename, height);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalArgumentException(wagonFilename);
}
}
}

LauncherPanel1

Class: jfreerails.launcher.LauncherPanel1

Documentation

No documentation available

Source Code

public LauncherPanel1(LauncherInterface owner) {
initComponents();
buttonModels[MODE_SINGLE_PLAYER] = singlePlayerButton.getModel();
buttonModels[MODE_START_NETWORK_GAME] = startNetworkButton.getModel();
buttonModels[MODE_JOIN_NETWORK_GAME] = joinNetworkButton.getModel();
buttonModels[MODE_SERVER_ONLY] = serverOnlyButton.getModel();
}

propertyChange

Class: jfreerails.launcher.ConnectedPlayersJPanel

Documentation

/** Called by the server when a player is added or removed. */

Source Code

/** Called by the server when a player is added or removed. */
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(FreerailsGameServer.CONNECTED_PLAYERS)) {
if (EventQueue.isDispatchThread()) {
updateListOfPlayers();
} else {
EventQueue.invokeLater(new Runnable() {
public void run() {
updateListOfPlayers();
}
});
}
}
}

getIndex

Class: jfreerails.move.RemoveItemFromListMove

Documentation

No documentation available

Source Code

public int getIndex() {
return index;
}

Called Methods

No outgoing method calls

TransferCargoAtStationMove

Class: jfreerails.move.TransferCargoAtStationMove

Documentation

No documentation available

Source Code

private TransferCargoAtStationMove(Move[] moves, boolean waiting) {
super(moves);
waitingForFullLoad = waiting;
}

setCameFrom

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

public void setCameFrom(Step v) {
this.cameFrom = v;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.move.ChangeProductionAtEngineShopMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = (before != null ? before.hashCode() : 0);
result = 29 * result + (after != null ? after.hashCode() : 0);
result = 29 * result + stationNumber;
result = 29 * result + principal.hashCode();
return result;
}

canBuildOnThisTerrainType

Class: jfreerails.world.track.TrackRule

Documentation

No documentation available

Source Code

boolean canBuildOnThisTerrainType(TerrainType.Category TerrainType);

Called Methods

No outgoing method calls

ImmutableSchedule

Class: jfreerails.world.train.ImmutableSchedule

Documentation

No documentation available

Source Code

public ImmutableSchedule(TrainOrdersModel[] orders, int gotoStation,
boolean hasPriorityOrders) {
this.orders = new ImList<TrainOrdersModel>(orders);
this.nextScheduledOrder = gotoStation;
this.hasPriorityOrders = hasPriorityOrders;
}

Called Methods

No outgoing method calls

createOverviewMap

Class: experimental.SimpleComponentFactoryImpl2

Documentation

No documentation available

Source Code

public JPanel createOverviewMap() {
if (null == this.overviewMap) {
// this.overviewMap = new OverviewMapJPanel();
this.overviewMap = new OverviewMapJComponent(r);
this.overviewMap.setup(new BlankMapRenderer(0.4F));
addMainMapAndOverviewMapMediatorIfNecessary();
}
return overviewMap;
// return new TestPanel();
}

getDx

Class: jfreerails.world.common.Step

Documentation

/** Returns the X component of the vector. */

Source Code

/** Returns the X component of the vector. */
public int getDx() {
return deltaX;
}

Called Methods

No outgoing method calls

generateTiles

Class: experimental.TrackTilesGenerator

Documentation

No documentation available

Source Code

private void generateTiles() {
for (TrackRule rule : rules) {
TrackRule.TrackCategories category = rule.getCategory();
Image icon;
if (category.equals(TrackRule.TrackCategories.bridge)
|| category.equals(TrackRule.TrackCategories.station)) {
tr.setIcon(rule.getTypeName());
icon = tr.icon;
} else {
icon = null;
}
if (category.equals(TrackRule.TrackCategories.tunnel)) {
tr.tunnel = true;
} else {
tr.tunnel = false;
}
tr.doubleTrack = rule.isDouble();
for (int i = 0; i < 512; i++) {
if (rule.testTrackPieceLegality(i)) {
String fileName = TrackPieceRendererImpl.generateFilename(
i, rule.getTypeName());
TrackConfiguration conf = TrackConfiguration
.from9bitTemplate(i);
Image smallImage = imageManager.newBlankImage(60, 60);
Graphics2D g2 = (Graphics2D) smallImage.getGraphics();
tr.paintTrackConf(g2, conf);
// Draw icon. Used for bridges and stations.
if (null != icon) {
int x = 30 - icon.getWidth(null) / 2;
int y = 30 - icon.getHeight(null) / 2;
g2.drawImage(icon, x, y, null);
}
g2.dispose();
imageManager.setImage(fileName, smallImage);
}
}
}
try {
imageManager.writeAllImages();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

read

Class: jfreerails.network.SynchronizedQueue

Documentation

No documentation available

Source Code

public synchronized FreerailsSerializable[] read() {
int length = queue.size();
FreerailsSerializable[] read = new FreerailsSerializable[length];
for (int i = 0; i < length; i++) {
read[i] = queue.removeFirst();
}
return read;
}

Called Methods

No outgoing method calls

testPlayers

Class: jfreerails.server.MapFixtureFactory2Test

Documentation

No documentation available

Source Code

public void testPlayers() {
assertEquals(4, w1.getNumberOfPlayers());
}

hashCode

Class: jfreerails.network.specifics.LogOnRequest

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = (username != null ? username.hashCode() : 0);
result = 29 * result + (password != null ? password.hashCode() : 0);
return result;
}

Called Methods

No outgoing method calls

testPickUpCargo2

Class: jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest

Documentation

/**
* Tests picking up cargo when the there is too much cargo at the station
* for the train to carry.
*/

Source Code

/**
* Tests picking up cargo when the there is too much cargo at the station
* for the train to carry.
*/
public void testPickUpCargo2() {
setCargoAtStation(this.cargoType0FromStation2, 200);
stopAtStation();
// The train has 3 wagons, each wagon carries 40 units of cargo, so
// the train should pickup 120 units of cargo.
MutableCargoBundle expectedOnTrain = new MutableCargoBundle();
expectedOnTrain.setAmount(this.cargoType0FromStation2, 120);
// The remaining 80 units of cargo should be left at the station.
MutableCargoBundle expectedAtStation = new MutableCargoBundle();
expectedAtStation.setAmount(this.cargoType0FromStation2, 80);
// Test the expected values against the actuals..
assertEquals(expectedOnTrain.toImmutableCargoBundle(),
getCargoOnTrain());
assertEquals(expectedAtStation.toImmutableCargoBundle(),
getCargoAtStation());
}

startThread

Class: jfreerails.launcher.Launcher

Documentation

/** Starts the server in a new thread. */

Source Code

/** Starts the server in a new thread. */
private static void startThread(final FreerailsGameServer server) {
try {
Runnable r = new Runnable() {
public void run() {
while (true) {
long startTime = System.currentTimeMillis();
server.update();
long deltatime = System.currentTimeMillis() - startTime;
if (deltatime < 20) {
try {
Thread.sleep(20 - deltatime);
} catch (InterruptedException e) {
// do nothing.
}
}
}
}
};
Thread t = new Thread(r, "FreerailsGameServer");
t.start();
} catch (Exception e) {
exit(e);
}
}

getBefore

Class: jfreerails.move.AddItemToSharedListMove

Documentation

No documentation available

Source Code

public FreerailsSerializable getBefore() {
return null;
}

Called Methods

No outgoing method calls

showTrainListActionPerformed

Class: experimental.DialogueBoxTester

Documentation

No documentation available

Source Code

private void showTrainListActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showTrainListActionPerformed
// Add your handling code here:
dialogueBoxController.showTrainList();
}// GEN-LAST:event_showTrainListActionPerformed

add

Class: experimental.GenerateDependenciesXmlAndHtml

Documentation

No documentation available

Source Code

private void add(String[] packageNames) {
assert started;
assert startedBlock;
String packagesString = "";
for (int i = packageNames.length - 1; i > 0; i--) {
packagesString += convertToPackageName(packageNames[i]) + ", ";
}
packagesString += " " + convertToPackageName(packageNames[0]);
// The html writer will use this later.
packages.add(packagesString);
xmlWriter.write("\n\t\t<!-- New row: " + packagesString + " -->\n");
xmlWriter.write("\t\t<echo message=\"New row: " + packagesString
+ "\"/>\n");
// Include the source files we are going to compile.
for (String packageName : packageNames) {
xmlWriter.write("\t\t<echo message=\"Check dependencies for "
+ packageName + "\"/>\n");
xmlWriter.write("\t\t<delete dir=\"temp\" />\n");
xmlWriter.write("\t\t<mkdir dir=\"temp\" />\n");
// First copy the files we are testing.
xmlWriter.write("\t\t<copy todir=\"temp\">\n");
xmlWriter.write("\t\t<fileset dir=\"src\">\n");
xmlWriter.write("\t\t\t<include name=\"" + packageName
+ ".java\" />\n");
// Exclude unit tests.
xmlWriter.write("\t\t\t<exclude name=\"**/*Test.java\" />\n");
xmlWriter.write("\t\t</fileset>\n");
xmlWriter.write("\t\t</copy>\n");
xmlWriter
.write("\t\t<javac fork=\"true\" srcdir=\"temp\" source=\"1.5\" classpath=\"dependencies\">\n");
// Include the files we are going to compile.
xmlWriter.write("\t\t\t<include name=\"" + packageName
+ ".java\" />\n");
xmlWriter.write("\t\t</javac>\n");
xmlWriter.write("\t\t<delete dir=\"temp\" />\n");
}
// Copy the files we have just tested to the dependencies directory.
xmlWriter.write("\t\t<copy todir=\"dependencies\">\n");
xmlWriter.write("\t\t<fileset dir=\"build\">\n");
for (int i = 0; i < packageNames.length; i++) {
xmlWriter.write("\t\t\t<include name=\"" + packageNames[i]
+ ".class\" />\n");
}
xmlWriter.write("\t\t\t<exclude name=\"**/*Test.class\" />\n");
xmlWriter.write("\t\t</fileset>\n");
xmlWriter.write("\t\t</copy>\n");
}

removeLastD1

Class: jfreerails.util.List2D

Documentation

No documentation available

Source Code

int removeLastD1();

Called Methods

No outgoing method calls

tryUndoMove

Class: jfreerails.move.RemoveItemFromListMove

Documentation

No documentation available

Source Code

public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
if (w.size(principal, listKey) < (index + 1)) {
return MoveStatus.moveFailed("w.size(listKey)="
+ w.size(principal, listKey) + " but index =" + index);
}
if (null != w.get(principal, listKey, index)) {
String reason = "The item at position " + index + " in the list ("
+ w.get(principal, listKey, index).toString()
+ ") is not the expected item (null).";
return MoveStatus.moveFailed(reason);
}
return MoveStatus.MOVE_OK;
}

getMoves

Class: jfreerails.move.CompositeMove

Documentation

No documentation available

Source Code

public final ImList<Move> getMoves() {
return moves;
}

Called Methods

No outgoing method calls

getLength

Class: jfreerails.world.track.TrackConfiguration

Documentation

/**
* Returns the length of track used in this configuration. Used to calculate
* the cost of building track.
*/

Source Code

/**
* Returns the length of track used in this configuration. Used to calculate
* the cost of building track.
*/
public int getLength() {
return length;
}

Called Methods

No outgoing method calls

firstScheduleStop

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

private int firstScheduleStop() {
return hasPriorityOrders ? 1 : 0;
}

Called Methods

No outgoing method calls

setUp

Class: jfreerails.move.ChangeTrackPieceMoveTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() {
setHasSetupBeenCalled(true);
setWorld(new WorldImpl(20, 20));
getWorld().set(ITEM.GAME_RULES, GameRules.NO_RESTRICTIONS);
MapFixtureFactory.generateTrackRuleList(getWorld());
}

getPlayer

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

No documentation available

Source Code

Player getPlayer(int i);

Called Methods

No outgoing method calls

TransactionAndTimeStamp

Class: jfreerails.world.accounts.TransactionAndTimeStamp

Documentation

No documentation available

Source Code

public TransactionAndTimeStamp(Transaction t, GameTime stamp) {
this.t = t;
timeStamp = stamp;
}

Called Methods

No outgoing method calls

removeLastD2

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

public void removeLastD2(int d1) {
super.removeLastList(d1);
}

MyGlassPanel

Class: jfreerails.client.common.MyGlassPanel

Documentation

No documentation available

Source Code

public MyGlassPanel() {
initComponents();
}

waitUntilFullJMenuItemActionPerformed

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void waitUntilFullJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_waitUntilFullJMenuItemActionPerformed
setWaitUntilFull(true);
}// GEN-LAST:event_waitUntilFullJMenuItemActionPerformed

createAdjacentCurve

Class: experimental.TrackRenderer

Documentation

No documentation available

Source Code

public static CubicCurve2D.Double createAdjacentCurve(
CubicCurve2D.Double c, double shift1, double shift2) {
Line2D.Double line1 = new Line2D.Double(c.getX1(), c.getY1(), c
.getCtrlX1(), c.getCtrlY1());
Line2D.Double line2 = new Line2D.Double(c.getX2(), c.getY2(), c
.getCtrlX2(), c.getCtrlY2());
line1 = createParallelLine(line1, shift1);
line2 = createParallelLine(line2, -shift2);
return new CubicCurve2D.Double(line1.x1, line1.y1, line1.x2, line1.y2,
line2.x2, line2.y2, line2.x1, line2.y1);
}

update

Class: jfreerails.server.TrackMaintenanceMoveGenerator

Documentation

No documentation available

Source Code

public void update(World w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
Move m = generateMove(w, principal, TRACK_MAINTENANCE);
moveReceiver.processMove(m);
m = generateMove(w, principal, STATION_MAINTENANCE);
moveReceiver.processMove(m);
}
}

init

Class: jfreerails.server.ServerGameModelImpl

Documentation

No documentation available

Source Code

public void init(MoveReceiver newMoveExecuter) {
this.moveExecuter = newMoveExecuter;
tb = new TrainUpdater(newMoveExecuter);
calcSupplyAtStations = new CalcSupplyAtStations(world, newMoveExecuter);
for (int i = 0; i < serverAutomata.size(); i++) {
serverAutomata.get(i).initAutomaton(newMoveExecuter);
}
tb.initAutomaton(newMoveExecuter);
nextModelUpdateDue = System.currentTimeMillis();
}

testAddingElementToList

Class: jfreerails.move.WorldDiffsMoveTest

Documentation

No documentation available

Source Code

public void testAddingElementToList() {
world.add(fp1, KEY.STATIONS, city1);
diffs.add(fp1, KEY.STATIONS, city2);
diffs.add(fp1, KEY.STATIONS, city2);
diffs.add(fp1, KEY.STATIONS, city2);
runTests();
}

getWaitUntilFull

Class: jfreerails.world.train.TrainOrdersModel

Documentation

No documentation available

Source Code

public boolean getWaitUntilFull() {
return waitUntilFull;
}

Called Methods

No outgoing method calls

initComponents

Class: jfreerails.controller.UnexpectedExceptionForm

Documentation

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/

Source Code

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
copyableTextJPanel1 = new jfreerails.controller.CopyableTextJPanel();
closebutton = new javax.swing.JButton();
getContentPane().setLayout(new java.awt.GridBagLayout());
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Unexpected Exception");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(copyableTextJPanel1, gridBagConstraints);
closebutton.setText("Close");
closebutton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
closebuttonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
getContentPane().add(closebutton, gridBagConstraints);
pack();
}

testHit4

Class: jfreerails.client.renderer.TrainRendererTest

Documentation

No documentation available

Source Code

@Test
public void testHit4() {
Point wagonCenter = new Point(100, 100);
Point mouseClick = new Point(84, 100);
boolean hit = isHit(wagonCenter, mouseClick, Step.NORTH);
assertFalse(hit);
}

getCategory

Class: jfreerails.world.track.TrackRule

Documentation

No documentation available

Source Code

TrackCategories getCategory();

Called Methods

No outgoing method calls

mousePressed

Class: jfreerails.client.view.MainMapAndOverviewMapMediator

Documentation

No documentation available

Source Code

@Override
public void mousePressed(MouseEvent evt) {
if (inside) {
draggingAndStartedInside = true;
}
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.move.NextActivityMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof NextActivityMove))
return false;
final NextActivityMove nextActivityMove = (NextActivityMove) o;
if (index != nextActivityMove.index)
return false;
if (!activity.equals(nextActivityMove.activity))
return false;
if (!principal.equals(nextActivityMove.principal))
return false;
return true;
}

Called Methods

No outgoing method calls

setCancelButtonActionListener

Class: jfreerails.client.view.TrainDialogueJPanel

Documentation

/**
* Removes any existing ActionListener listeners from the cancel button,
* then adds the specified one.
*/

Source Code

/**
* Removes any existing ActionListener listeners from the cancel button,
* then adds the specified one.
*/
void setCancelButtonActionListener(ActionListener l) {
ActionListener[] oldListeners = closeJButton.getActionListeners();
for (int i = 0; i < oldListeners.length; i++) {
closeJButton.removeActionListener(oldListeners[i]);
}
this.closeJButton.addActionListener(l);
}

Called Methods

No outgoing method calls

getUpdatedTiles

Class: jfreerails.move.MapUpdateMove

Documentation

No documentation available

Source Code

Rectangle getUpdatedTiles();

Called Methods

No outgoing method calls

dumpImages

Class: jfreerails.client.renderer.ForestStyleTileRenderer

Documentation

No documentation available

Source Code

@Override
public void dumpImages(ImageManager imageManager) {
for (int i = 0; i < this.getTileIcons().length; i++) {
String fileName = generateRelativeFileName(i);
imageManager.setImage(fileName, this.getTileIcons()[i]);
}
}

setArray

Class: jfreerails.util.GrowableBase

Documentation

/**
* Set the backing array. This method is used by the type-agnostic base
* class code to set the array used for type-specific storage by the child
* class.
*
*/

Source Code

/**
* Set the backing array. This method is used by the type-agnostic base
* class code to set the array used for type-specific storage by the child
* class.
*
*/
protected abstract void setArray(Object array);

Called Methods

No outgoing method calls

initComponents

Class: jfreerails.client.view.TrainDescriptionJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jLabel1 = new javax.swing.JLabel();
trainViewJPanel1 = new jfreerails.client.view.TrainListCellRenderer();
setLayout(new java.awt.GridBagLayout());
setBorder(new javax.swing.border.TitledBorder("Current Details"));
setPreferredSize(new java.awt.Dimension(250, 97));
jLabel1.setFont(new java.awt.Font("Dialog", 0, 12));
jLabel1
.setText("<html><head></head><body>Trains X: 20 passengers, 15 tons of mfg goods, 12 sacks of mail, and 7 tons of livestock.</body></html>");
jLabel1.setMinimumSize(new java.awt.Dimension(250, 17));
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.LEADING);
jLabel1.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jLabel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
add(trainViewJPanel1, gridBagConstraints);
}// GEN-END:initComponents

Called Methods

No outgoing method calls

drawTrackPieceIcon

Class: jfreerails.client.renderer.TrackPieceRendererImpl

Documentation

No documentation available

Source Code

public void drawTrackPieceIcon(int trackTemplate, java.awt.Graphics g,
int x, int y, java.awt.Dimension tileSize) {
if ((trackTemplate > 511) || (trackTemplate < 0)) {
throw new java.lang.IllegalArgumentException("trackTemplate = "
+ trackTemplate + ", it should be in the range 0-511");
}
if (trackPieceIcons[trackTemplate] != null) {
int drawX = x * tileSize.width - tileSize.width / 2;
int drawY = y * tileSize.height - tileSize.height / 2;
g.drawImage(trackPieceIcons[trackTemplate], drawX, drawY, null);
}
}

Called Methods

No outgoing method calls

check4overlap

Class: jfreerails.move.ChangeTrackPieceMove

Documentation

/**
* This method may be called under 3 possible conditions: (1) when a station
* is getting built, (2) when a station is getting upgraded, (3) when a
* station is getting removed.
*/

Source Code

/**
* This method may be called under 3 possible conditions: (1) when a station
* is getting built, (2) when a station is getting upgraded, (3) when a
* station is getting removed.
*/
protected static MoveStatus check4overlap(World w, ImPoint location,
TrackPiece trackPiece) {
/*
* Fix for 915945 (Stations should not overlap) Check that there is not
* another station whose radius overlaps with the one we are building.
*/
TrackRule thisStationType = trackPiece.getTrackRule();
assert thisStationType.isStation();
for (int player = 0; player < w.getNumberOfPlayers(); player++) {
FreerailsPrincipal principal = w.getPlayer(player).getPrincipal();
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
while (wi.next()) {
StationModel station = (StationModel) wi.getElement();
/*
* Fix for bug 948675 - Can't upgrade station types If locations
* are the same, then we are upgrading a station so it doesn't
* matter if the radii overlap.
*/
if (location.x == station.x && location.y == station.y) {
continue;
}
FreerailsTile tile = (FreerailsTile) w.getTile(station.x,
station.y);
TrackRule otherStationType = tile.getTrackPiece().getTrackRule();
assert otherStationType.isStation();
int sumOfRadii = otherStationType.getStationRadius()
+ thisStationType.getStationRadius();
int sumOfRadiiSquared = sumOfRadii * sumOfRadii;
int xDistance = station.x - location.x;
int yDistance = station.y - location.y;
// Do radii overlap?
boolean xOverlap = sumOfRadiiSquared >= (xDistance * xDistance);
boolean yOverlap = sumOfRadiiSquared >= (yDistance * yDistance);
if (xOverlap && yOverlap) {
String message = "Too close to " + station.getStationName();
return MoveStatus.moveFailed(message);
}
}
}
return MoveStatus.MOVE_OK;
}

makeInsertSpace

Class: jfreerails.util.ArrayBase

Documentation

/**
* Makes room to insert a value at a specified index in the array.
*
* @param index
* index position at which to insert element
*/

Source Code

/**
* Makes room to insert a value at a specified index in the array.
*
* @param index
* index position at which to insert element
*/
protected void makeInsertSpace(int index) {
if (index >= 0 && index <= countPresent) {
if (++countPresent > countLimit) {
growArray(countPresent);
}
if (index < countPresent - 1) {
Object array = getArray();
System.arraycopy(array, index, array, index + 1, countPresent
- index - 1);
}
} else {
throw new ArrayIndexOutOfBoundsException("Invalid index value");
}
}

setMoveFork

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public void setMoveFork(MoveChainFork moveFork) {
this.moveFork = moveFork;
}

Called Methods

No outgoing method calls

set

Class: jfreerails.util.List1DImpl

Documentation

No documentation available

Source Code

public void set(int i, T element) {
elementData.set(i, element);
}

Called Methods

No outgoing method calls

MutableSchedule

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public MutableSchedule() {
}

Called Methods

No outgoing method calls

actionPerformed

Class: jfreerails.client.view.NewGameAction

Documentation

No documentation available

Source Code

public void actionPerformed(ActionEvent e) {
String mapName = e.getActionCommand();
if (mapName != null) {
Message2Server message2 = new NewGameMessage2Server(1, mapName);
modelRoot.sendCommand(message2);
}
}

mouseDragged

Class: jfreerails.client.view.MainMapAndOverviewMapMediator

Documentation

No documentation available

Source Code

@Override
public void mouseDragged(MouseEvent evt) {
if (draggingAndStartedInside) {
/*
* Rectangle r= overviewMapJPanel.mainMapVisibleRect;
* r.x+=evt.getX()-lastMouseLocation.x;
* r.y+=evt.getY()-lastMouseLocation.y;
* lastMouseLocation.x=evt.getX(); lastMouseLocation.y=evt.getY();
*
* updateInside(evt); overviewMapJPanel.repaint();
*/
int deltaX = evt.getX() - lastMouseLocation.x;
int deltaY = evt.getY() - lastMouseLocation.y;
lastMouseLocation.x = evt.getX();
lastMouseLocation.y = evt.getY();
// float overviewScale=overviewMapJPanel.getScale();
// float mainMapScale=mainMap.getScale();
int overviewScale = overviewMapJPanel.getPreferredSize().width;
int mainMapScale = mainMap.getWidth();
int scaledDeltaX = (deltaX * mainMapScale / overviewScale);
int scaledDeltaY = (deltaY * mainMapScale / overviewScale);
Rectangle r = mainMap.getVisibleRect();
r.x += scaledDeltaX;
r.y += scaledDeltaY;
mainMap.scrollRectToVisible(r);
updateInside(evt);
}
}

getName

Class: jfreerails.world.player.WorldPrincipal

Documentation

No documentation available

Source Code

public String getName() {
return principalName;
}

Called Methods

No outgoing method calls

getElementAt

Class: jfreerails.client.view.World2ListModelAdapter

Documentation

No documentation available

Source Code

public Object getElementAt(int i) {
elements.gotoRow(i);
return elements.getElement();
}

SimpleTileRenderer

Class: jfreerails.client.top.SimpleTileRenderer

Documentation

No documentation available

Source Code

public SimpleTileRenderer() {
}

Called Methods

No outgoing method calls

AbstractInetConnection

Class: jfreerails.network.AbstractInetConnection

Documentation

No documentation available

Source Code

public AbstractInetConnection(Socket s) throws IOException {
inetConnection = new InetConnection(s);
open();
}

incrementRunningTotal

Class: jfreerails.world.top.TransactionAggregator

Documentation

No documentation available

Source Code

protected void incrementRunningTotal(int transactionID) {
Transaction t = w.getTransaction(principal, transactionID);
runningTotal += t.deltaCash().getAmount();
}

setTimeOut

Class: jfreerails.network.AbstractInetConnection

Documentation

No documentation available

Source Code

void setTimeOut(int i) {
timeout = i;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.station.Demand4Cargo

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Demand4Cargo))
return false;
final Demand4Cargo demandAtStation = (Demand4Cargo) o;
if (!demand.equals(demandAtStation.demand))
return false;
return true;
}

reactToUpdate

Class: jfreerails.client.view.StationInfoJPanel

Documentation

No documentation available

Source Code

private void reactToUpdate(KEY key, int changedIndex, boolean isAddition) {
if (!isVisible()) {
return;
}
int currentIndex = wi.getIndex();
if (key == KEY.CARGO_BUNDLES) {
if (changedIndex == cargoBundleIndex) {
/* update our cargo bundle */
display();
return;
}
} else if (key == KEY.STATIONS) {
wi.reset();
if (currentIndex != WorldIterator.BEFORE_FIRST) {
if (currentIndex < wi.size()) {
wi.gotoIndex(currentIndex);
} else {
currentIndex = WorldIterator.BEFORE_FIRST;
}
}
if (isAddition && wi.getIndex() == WorldIterator.BEFORE_FIRST) {
if (wi.next()) {
display();
}
}
if (currentIndex == changedIndex
|| currentIndex == WorldIterator.BEFORE_FIRST) {
display();
}
}
return;
}

listSize

Class: jfreerails.world.top.NonNullElements

Documentation

No documentation available

Source Code

private int listSize() {
if (null == this.skey) {
return w.size(principal, key);
}
return w.size(this.skey);
}

getNumOrders

Class: jfreerails.world.train.Schedule

Documentation

/**
* Returns number of non priority orders + number of priority orders.
*
* @return Number of orders.
*/

Source Code

/**
* Returns number of non priority orders + number of priority orders.
*
* @return Number of orders.
*/
int getNumOrders();

Called Methods

No outgoing method calls

testAllClasses

Class: experimental.CheckFreerailsSerializableClasses

Documentation

No documentation available

Source Code

@SuppressWarnings("unchecked")
static void testAllClasses() {
ClassLocater locater = new ClassLocater();
Class[] classes = locater.getSubclassesOf(FreerailsSerializable.class);
int classesWithProblems = 0;
for (Class clazz : classes) {
if (clazz.isInterface()) {
logger.fine("Skipping interface " + clazz.getName());
continue;
}
int mods = clazz.getModifiers();
if ((mods & Modifier.ABSTRACT) != 0) {
logger.fine("Skipping abstract class " + clazz.getName());
continue;
}
if (clazz.isAnnotationPresent(InstanceControlled.class)) {
logger.fine("Skipping InstanceControlled class "
+ clazz.getName());
continue;
}
boolean b = overridesHashCodeAndEquals(clazz);
b = b && checkFields(clazz);
if (!b) {
classesWithProblems++;
}
}
System.err.println(classes.length + " classes checked, "
+ classesWithProblems + " have problems");
}

getState

Class: jfreerails.world.train.TrainMotion

Documentation

/**
* Returns the train's position at the specified time.
*
* @param t
* the time.
* @return the train's position.
* @throws IllegalArgumentException
* if t is outside the interval
*/

Source Code

/**
* Returns the train's position at the specified time.
*
* @param t
* the time.
* @return the train's position.
* @throws IllegalArgumentException
* if t is outside the interval
*/
public TrainPositionOnMap getState(double t) {
t = Math.min(t, speeds.getT());
double offset = calcOffSet(t);
FreerailsPathIterator pathIt = path.subPath(offset, trainLength);
double speed = speeds.calcV(t);
double acceleration = speeds.calcA(t);
TrainPositionOnMap tpom = TrainPositionOnMap
.createInSameDirectionAsPath(pathIt, speed, acceleration,
activity);
return tpom.reverse();
}

getPrincipal

Class: jfreerails.world.player.Player

Documentation

No documentation available

Source Code

public FreerailsPrincipal getPrincipal() {
return principal;
}

Called Methods

No outgoing method calls

BrokerJFrame

Class: jfreerails.client.view.BrokerJFrame

Documentation

No documentation available

Source Code

public BrokerJFrame(String html) {
initComponents();
setHtml(html);
}

processMove

Class: jfreerails.network.specifics.MoveReceiver

Documentation

No documentation available

Source Code

void processMove(Move move);

Called Methods

No outgoing method calls

toInt

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

public static int toInt(int x, int y) {
int i = x | (y << BITS_FOR_COORDINATE);
return i;
}

Called Methods

No outgoing method calls

addPropertyChangeListener

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public void addPropertyChangeListener(ModelRootListener l) {
listeners.add(l);
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.controller.AddStationPreMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = p.hashCode();
result = 29 * result + ruleNumber;
result = 29 * result + principal.hashCode();
return result;
}

selectAllItemActionPerformed

Class: jfreerails.controller.CopyableTextJPanel

Documentation

No documentation available

Source Code

private void selectAllItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectAllItemActionPerformed
jTextArea1.selectAll();
}//GEN-LAST:event_selectAllItemActionPerformed

Called Methods

No outgoing method calls

getTrackGraphicID

Class: jfreerails.world.track.TrackPieceImpl

Documentation

No documentation available

Source Code

public int getTrackGraphicID() {
return configuration.getTrackGraphicsID();
}

TrackLayer

Class: jfreerails.client.renderer.TrackLayer

Documentation

No documentation available

Source Code

public TrackLayer(ReadOnlyWorld world,
RenderersRoot trackPieceViewList) {
this.rr = trackPieceViewList;
this.w = world;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.train.CompositeSpeedAgainstTime

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof CompositeSpeedAgainstTime))
return false;
final CompositeSpeedAgainstTime compositeSpeedAgainstTime = (CompositeSpeedAgainstTime) o;
if (finalT != compositeSpeedAgainstTime.finalT)
return false;
if (finalS != compositeSpeedAgainstTime.finalS)
return false;
if (!values.equals(compositeSpeedAgainstTime.values))
return false;
return true;
}

renderTile

Class: jfreerails.client.renderer.TileRenderer

Documentation

No documentation available

Source Code

void renderTile(java.awt.Graphics g, int renderX, int renderY, int mapX,
int mapY, ReadOnlyWorld w);

Called Methods

No outgoing method calls

testMoveTrackExplorer

Class: jfreerails.controller.FlatTrackExplorerTest

Documentation

/**
* Tests that we can move the track explorer at point 10,10 northeast, and
* that when we have done this, we can move it back again.
*/

Source Code

/**
* Tests that we can move the track explorer at point 10,10 northeast, and
* that when we have done this, we can move it back again.
*/
public void testMoveTrackExplorer() {
setUp();
FlatTrackExplorer fte;
PositionOnTrack p = PositionOnTrack.createComingFrom(10, 10, Step.EAST);
fte = new FlatTrackExplorer(world, p);
PositionOnTrack pos = new PositionOnTrack(fte.getPosition());
assertEquals(10, pos.getX());
assertEquals(10, pos.getY());
assertTrue(fte.hasNextEdge());
fte.nextEdge();
pos.setValuesFromInt(fte.getVertexConnectedByEdge());
assertEquals(Step.NORTH_EAST, pos.cameFrom());
assertEquals(11, pos.getX());
assertEquals(9, pos.getY());
int branchPosition = fte.getVertexConnectedByEdge();
fte.moveForward();
assertEquals(branchPosition, fte.getPosition());
pos.setValuesFromInt(fte.getPosition());
assertEquals(11, pos.getX());
assertEquals(9, pos.getY());
assertTrue(fte.hasNextEdge());
fte.nextEdge();
assertEquals(Step.SOUTH_WEST, fte.currentBranch.cameFrom());
assertTrue(!fte.hasNextEdge());
fte.moveForward();
pos.setValuesFromInt(fte.getPosition());
assertEquals(10, pos.getX());
assertEquals(10, pos.getY());
}

getStationChooseActions

Class: jfreerails.client.view.StationBuildModel

Documentation

No documentation available

Source Code

public Action[] getStationChooseActions() {
return stationChooseActions.toArray(new Action[stationChooseActions.size()]);
}

Called Methods

No outgoing method calls

buildTrains

Class: jfreerails.server.TrainUpdater

Documentation

/**
* Iterator over the stations and build trains at any that have their
* production field set.
*
*/

Source Code

/**
* Iterator over the stations and build trains at any that have their
* production field set.
*
*/
void buildTrains(ReadOnlyWorld world) {
for (int k = 0; k < world.getNumberOfPlayers(); k++) {
FreerailsPrincipal principal = world.getPlayer(k).getPrincipal();
for (int i = 0; i < world.size(principal, KEY.STATIONS); i++) {
StationModel station = (StationModel) world.get(principal,
KEY.STATIONS, i);
if (null != station) {
ImList<PlannedTrain> production = station
.getProduction();
if (production.size() > 0) {
ImPoint p = new ImPoint(station.x, station.y);
for (int j = 0; j < production.size(); j++) {
int engineType = production.get(j).getEngineType();
ImInts wagonTypes = production.get(j)
.getWagonTypes();
this.buildTrain(engineType, wagonTypes, p,
principal, world);
// TrainMover trainMover =
// this.buildTrain(engineType, wagonTypes, p,
// principal, world);
// this.addTrainMover(trainMover);
}
ChangeProductionAtEngineShopMove move = new ChangeProductionAtEngineShopMove(
production,
new ImList<PlannedTrain>(), i,
principal);
moveReceiver.processMove(move);
}
}
}
}
}

setUp

Class: jfreerails.controller.BuildTrackExplorerTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
world = new WorldImpl(20, 20);
world.addPlayer(testPlayer);
world.set(ITEM.GAME_RULES, GameRules.NO_RESTRICTIONS);
principal = testPlayer.getPrincipal();
MapFixtureFactory.generateTrackRuleList(world);
}

AddTrainPreMove

Class: jfreerails.controller.AddTrainPreMove

Documentation

No documentation available

Source Code

public AddTrainPreMove(int e, ImInts wags, ImPoint p,
FreerailsPrincipal fp, ImmutableSchedule s) {
engineTypeId = e;
wagons = wags;
point = p;
principal = fp;
schedule = s;
if (null == wags) {
throw new NullPointerException();
}
if (null == p) {
throw new NullPointerException();
}
if (null == fp) {
throw new NullPointerException();
}
if (null == s) {
throw new NullPointerException();
}
}

Called Methods

No outgoing method calls

createOverviewMap

Class: jfreerails.client.top.GUIComponentFactoryTestImpl

Documentation

No documentation available

Source Code

public JPanel createOverviewMap() {
return mapOverview;
}

Called Methods

No outgoing method calls

start_Cargo_Types

Class: jfreerails.server.parser.CargoAndTerrainHandlerImpl

Documentation

No documentation available

Source Code

public void start_Cargo_Types(final Attributes meta) throws SAXException {
// no need to do anything here.
}

Called Methods

No outgoing method calls

getKeyID

Class: jfreerails.world.top.SKEY

Documentation

No documentation available

Source Code

int getKeyID() {
return keyNumber;
}

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.view.DialogueBoxController

Documentation

/**
* Called when a new game is started or a game is loaded.
* <p>
* <b>Be extremely careful with the references of objects allocated in this
* method to avoid memory leaks - see bug 967677 (OutOfMemoryError after
* starting several new games). </b>
* </p>
*/

Source Code

/**
* Called when a new game is started or a game is loaded.
* <p>
* <b>Be extremely careful with the references of objects allocated in this
* method to avoid memory leaks - see bug 967677 (OutOfMemoryError after
* starting several new games). </b>
* </p>
*/
public void setup(ModelRootImpl mr, RenderersRoot vl) {
this.modelRoot = mr;
this.vl = vl;
modelRoot.addListListener(this); // When a new train gets built, we
// show the train info etc
this.world = modelRoot.getWorld();
if (world == null)
throw new NullPointerException();
if (vl == null)
throw new NullPointerException();
// Setup the various dialogue boxes.
// setup the terrain info dialogue.
terrainInfo.setup(world, vl);
// setup the supply and demand at station dialogue.
stationInfo.setup(modelRoot, vl, this.closeCurrentDialogue);
modelRoot.addListListener(stationInfo);
// setup the 'show controls' dialogue
showControls.setup(this.modelRoot, vl, this.closeCurrentDialogue);
about.setup(this.modelRoot, vl, this.closeCurrentDialogue);
how2play.setup(this.modelRoot, vl, this.closeCurrentDialogue);
javaProperties.setup(this.modelRoot, vl, this.closeCurrentDialogue);
// Set up train orders dialogue
// trainScheduleJPanel = new TrainScheduleJPanel();
// trainScheduleJPanel.setup(w, vl);
// moveChainFork.add(trainScheduleJPanel);
// Set up select engine dialogue.
selectEngine.setCancelButtonActionListener(this.closeCurrentDialogue);
selectEngine.setup(modelRoot, vl, selectEngineAction);
newspaper.setup(modelRoot, vl, closeCurrentDialogue);
selectWagons.setup(modelRoot, vl, selectWagonsAction);
trainDialogueJPanel.setup(modelRoot, vl, this.closeCurrentDialogue);
modelRoot.addListListener(trainDialogueJPanel);
trainDialogueJPanel
.setTrainDetailsButtonActionListener(trainDetailsButtonActionListener);
trainDialogueJPanel
.setCancelButtonActionListener(this.closeCurrentDialogue);
}

hasNextInt

Class: jfreerails.server.TrainPathFinder

Documentation

No documentation available

Source Code

public boolean hasNextInt() {
boolean moving = stopsHandler.isTrainMoving();
if (moving) {
return trackExplorer.hasNextEdge();
}
mr.processMove(stopsHandler.getMoves());
return false;
}

exit

Class: jfreerails.launcher.Launcher

Documentation

No documentation available

Source Code

private static void exit(Exception e) {
ReportBugTextGenerator.unexpectedException(e);
}

getNumOrders

Class: jfreerails.world.train.ImmutableSchedule

Documentation

No documentation available

Source Code

public int getNumOrders() {
return orders.size();
}

getPrice

Class: jfreerails.world.train.EngineType

Documentation

No documentation available

Source Code

public Money getPrice() {
return price;
}

Called Methods

No outgoing method calls

tryDoMove

Class: jfreerails.controller.SimpleMoveExecutor

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(Move m) {
return m.tryDoMove(w, p);
}

RemoveStationMove

Class: jfreerails.move.RemoveStationMove

Documentation

No documentation available

Source Code

private RemoveStationMove(ArrayList<Move> moves) {
super(moves);
}

renderTile

Class: jfreerails.client.renderer.SpecialTileRenderer

Documentation

No documentation available

Source Code

@Override
public void renderTile(java.awt.Graphics g, int renderX, int renderY,
int mapX, int mapY, ReadOnlyWorld w) {
if (parentTileView != null) {
parentTileView.renderTile(g, renderX, renderY, mapX, mapY, w);
} else {
logger.warning("parent tileView==null");
}
Image icon = this.getIcon(mapX, mapX, w);
if (null != icon) {
g.drawImage(icon, renderX, renderY, null);
} else {
logger.warning("special tileView icon==null");
}
}

isPlayer

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

No documentation available

Source Code

boolean isPlayer(FreerailsPrincipal p);

Called Methods

No outgoing method calls

paintTile

Class: jfreerails.client.renderer.SquareTileBackgroundRenderer

Documentation

No documentation available

Source Code

public void paintTile(Graphics g, int tileX, int tileY) {
mapView.paintTile(g, tileX, tileY);
}

findMaintenanceCost

Class: jfreerails.client.view.TrainSummaryJPanel

Documentation

No documentation available

Source Code

private String findMaintenanceCost() {
GameTime time = w.currentTime();
GameCalendar gameCalendar = (GameCalendar) w.get(ITEM.CALENDAR);
double month = gameCalendar.getMonth(time.getTicks());
long cost = (long) (month / 12 * 5000);
Money m = new Money(cost);
return "$" + m.toString();
}

setUp

Class: jfreerails.controller.TrackBuildingTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
super.setUp();
w = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(w, 0);
ModelRoot mr = new ModelRootImpl();
producer = new TrackMoveProducer(me, w, mr);
FreerailsPrincipal principal = w.getPlayer(0).getPrincipal();
pathFinder = new TrackPathFinder(w, principal);
stationBuilder = new StationBuilder(me);
bts = BuildTrackStrategy.getDefault(w);
}

update

Class: jfreerails.network.EchoGameServer

Documentation

No documentation available

Source Code

public void update() {
synchronized (this) {
/* Read messages. */
for (int i = 0; i < connections.size(); i++) {
Connection2Client connection = connections.get(i);
try {
FreerailsSerializable[] messages = connection
.readFromClient();
for (int j = 0; j < messages.length; j++) {
messages2send.add(messages[j]);
}
} catch (IOException e) {
try {
if (connection.isOpen()) {
connection.disconnect();
}
} catch (IOException e1) {
//
e1.printStackTrace();
}
}
}
/* Send messages. */
Iterator<FreerailsSerializable> messagesIterator = messages2send
.iterator();
while (messagesIterator.hasNext()) {
FreerailsSerializable message = messagesIterator.next();
sendMessage(message);
}
}
}

MoveStatus

Class: jfreerails.move.MoveStatus

Documentation

No documentation available

Source Code

private MoveStatus(boolean ok, String mess) {
if(ok){
t = null;
}else{
t = new Throwable();
t.fillInStackTrace();
}
this.ok = ok;
this.message = mess;
}

Called Methods

No outgoing method calls

getMaintenanceCost

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

public Money getMaintenanceCost() {
return new Money(0);
}

Called Methods

No outgoing method calls

read

Class: jfreerails.util.FlowRateInputStream

Documentation

No documentation available

Source Code

@Override
public int read(byte[] b, int off, int len) throws IOException {
int r = super.in.read(b, off, len);
totalByteReceived += r;
return r;
}

Called Methods

No outgoing method calls

stopsAtStation

Class: jfreerails.world.train.ImmutableSchedule

Documentation

No documentation available

Source Code

public boolean stopsAtStation(int stationNumber) {
for (int i = 0; i < this.getNumOrders(); i++) {
TrainOrdersModel order = this.getOrder(i);
if (order.getStationID() == stationNumber) {
return true;
}
}
return false;
}

setUp

Class: jfreerails.server.TrackMaintenanceMoveGeneratorTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
w = new WorldImpl(20, 20);
w.addPlayer(MapFixtureFactory.TEST_PLAYER);
MapFixtureFactory.generateTrackRuleList(w);
}

storeRunningTotal

Class: jfreerails.world.top.TransactionAggregator

Documentation

/**
* Stores the current running total in the totals array at the specified
* position.
*/

Source Code

/**
* Stores the current running total in the totals array at the specified
* position.
*/
protected void storeRunningTotal(int timeIndex) {
monetaryTotals[timeIndex] = new Money(runningTotal);
}

Called Methods

No outgoing method calls

getSpeed

Class: jfreerails.world.common.GameSpeed

Documentation

No documentation available

Source Code

public int getSpeed() {
return speed;
}

Called Methods

No outgoing method calls

CargoBatch

Class: jfreerails.world.cargo.CargoBatch

Documentation

No documentation available

Source Code

public CargoBatch(int type, int x, int y, long time, int origin) {
cargoType = type;
sourceX = x;
sourceY = y;
timeCreated = time;
stationOfOrigin = origin;
}

Called Methods

No outgoing method calls

createDisplayMenu

Class: experimental.SimpleComponentFactoryImpl2

Documentation

No documentation available

Source Code

public JMenu createDisplayMenu() {
JMenu displayMenu = new JMenu("Display");
addMainmapzoomMenuItem(displayMenu, 5);
addMainmapzoomMenuItem(displayMenu, 10);
addOverviewmapzoomMenuItem(displayMenu, 0.2F);
addOverviewmapzoomMenuItem(displayMenu, 0.6F);
return displayMenu;
}

showControlsActionPerformed

Class: experimental.DialogueBoxTester

Documentation

No documentation available

Source Code

private void showControlsActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showControlsActionPerformed
// Add your handling code here:
dialogueBoxController.showGameControls();
}// GEN-LAST:event_showControlsActionPerformed

getPrincipal

Class: jfreerails.controller.SimpleMoveExecutor

Documentation

No documentation available

Source Code

public FreerailsPrincipal getPrincipal() {
return p;
}

Called Methods

No outgoing method calls

selectTrainOrdersActionPerformed

Class: experimental.DialogueBoxTester

Documentation

No documentation available

Source Code

private void selectTrainOrdersActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_selectTrainOrdersActionPerformed
// Add your handling code here:
trainDialogueJPanel.setup(modelRoot, vl, closeCurrentDialogue);
trainDialogueJPanel.display(0);
dialogueBoxController.showContent(trainDialogueJPanel);
}// GEN-LAST:event_selectTrainOrdersActionPerformed

beforeEqualsAfter

Class: jfreerails.move.ChangeItemInListMove

Documentation

No documentation available

Source Code

public boolean beforeEqualsAfter(){
return Utils.equal(this.before, this.after);
}

hashCode

Class: jfreerails.world.cargo.CargoBatch

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result = 17;
result = 37 * result + this.cargoType;
result = 37 * result + this.sourceX;
result = 37 * result + this.sourceY;
result = 37 * result + this.stationOfOrigin;
result = 37 * result
+ (int) (this.timeCreated ^ (this.timeCreated >>> 32));
return result;
}

Called Methods

No outgoing method calls

getTrackTypeID

Class: jfreerails.world.track.NullTrackPiece

Documentation

No documentation available

Source Code

public int getTrackTypeID() {
return NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER;
}

Called Methods

No outgoing method calls

StationInfoJPanel

Class: jfreerails.client.view.StationInfoJPanel

Documentation

No documentation available

Source Code

public StationInfoJPanel() {
initComponents();
}

toString

Class: jfreerails.world.common.IntLine

Documentation

No documentation available

Source Code

@Override
public String toString() {
return "(" + x1 + ", " + y1 + ", " + x2 + ", " + y2 + ")";
}

Called Methods

No outgoing method calls

canRemoveFromTail

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public boolean canRemoveFromTail(TrainPositionOnMap b) {
if (tailsAreEqual(this, b)) {
FreerailsPathIterator path = b.reversePath();
int i = this.getLength() - 1;
IntLine line = new IntLine();
while (path.hasNext()) {
path.nextSegment(line);
if (this.getX(i) != line.x1 || this.getY(i) != line.y1) {
return false;
}
i--;
}
return true;
}
return false;
}

main

Class: jfreerails.world.track.LegalTrackConfigurationsTest

Documentation

No documentation available

Source Code

public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}

spaceAvailable2

Class: jfreerails.controller.TrainAccessor

Documentation

No documentation available

Source Code

public static ImInts spaceAvailable2(ReadOnlyWorld row, ImmutableCargoBundle onTrain, ImInts consist){
// This array will store the amount of space available on the train for
// each cargo type.
final int NUM_CARGO_TYPES = row.size(SKEY.CARGO_TYPES);
int[] spaceAvailable = new int[NUM_CARGO_TYPES];
// First calculate the train's total capacity.
for (int j = 0; j < consist.size(); j++) {
int cargoType = consist.get(j);
spaceAvailable[cargoType] += WagonType.UNITS_OF_CARGO_PER_WAGON;
}
for (int cargoType = 0; cargoType < NUM_CARGO_TYPES; cargoType++) {
spaceAvailable[cargoType]= spaceAvailable[cargoType] - onTrain.getAmount(cargoType);
}
return new ImInts(spaceAvailable);
}

canBuyStock

Class: jfreerails.controller.FinancialDataGatherer

Documentation

No documentation available

Source Code

public boolean canBuyStock() {
return totalShares > 0;
}

Called Methods

No outgoing method calls

initComponents

Class: jfreerails.client.view.TrainDialogueJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
newTrainScheduleJPanel1 = new jfreerails.client.view.TrainScheduleJPanel();
trainDetailsJPanel1 = new TrainDescriptionJPanel();
previousJButton = new javax.swing.JButton();
nextJButton = new javax.swing.JButton();
trainListJButton = new javax.swing.JButton();
closeJButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(510, 400));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(newTrainScheduleJPanel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
add(trainDetailsJPanel1, gridBagConstraints);
previousJButton.setText("last");
previousJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
previousJButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(previousJButton, gridBagConstraints);
nextJButton.setText("next");
nextJButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextJButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(nextJButton, gridBagConstraints);
trainListJButton.setText("Train list");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(trainListJButton, gridBagConstraints);
closeJButton.setText("Close");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 3;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
add(closeJButton, gridBagConstraints);
}// GEN-END:initComponents

hashCode

Class: jfreerails.move.AddTransactionMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = transaction.hashCode();
result = 29 * result + principal.hashCode();
result = 29 * result + (constrained ? 1 : 0);
return result;
}

Called Methods

No outgoing method calls

isEnableDoubleTrack

Class: jfreerails.world.track.TrackRuleProperties

Documentation

No documentation available

Source Code

public boolean isEnableDoubleTrack() {
return enableDoubleTrack;
}

Called Methods

No outgoing method calls

paint

Class: jfreerails.client.renderer.StationRadiusRenderer

Documentation

No documentation available

Source Code

public void paint(Graphics2D g) {
if (modelRoot.getProperty(ModelRoot.Property.CURSOR_MODE).equals(
Value.PLACE_STATION_CURSOR_MODE)) {
g.setStroke(new BasicStroke(2f));
g.setColor(borderColor);
g.drawRect(tileSize * (x - radius), tileSize * (y - radius),
tileSize * (2 * radius + 1), tileSize * (2 * radius + 1));
}
}

setup

Class: jfreerails.client.view.SaveGameJPanel

Documentation

No documentation available

Source Code

public void setup(ModelRoot m, RenderersRoot vl,
Action closeAction) {
this.close = closeAction;
this.modelRoot = m;
}

Called Methods

No outgoing method calls

addD1

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

public int addD1() {
return super.addDimension();
}

actionPerformed

Class: jfreerails.client.view.BuildTrainDialogAction

Documentation

No documentation available

Source Code

public void actionPerformed(ActionEvent e) {
if (dialogueBoxController != null) {
dialogueBoxController.showSelectEngine();
}
}

redoMoves

Class: jfreerails.move.CompositeMove

Documentation

No documentation available

Source Code

private void redoMoves(World w, int number, FreerailsPrincipal p) {
for (int i = number; i < moves.size(); i++) {
MoveStatus ms = moves.get(i).doMove(w, p);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
}
}

calculateDistance

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public double calculateDistance() {
double distance = 0;
IntLine line = new IntLine();
FreerailsPathIterator path = this.path();
while (path.hasNext()) {
path.nextSegment(line);
int sumOfSquares = (line.x1 - line.x2) * (line.x1 - line.x2)
+ (line.y1 - line.y2) * (line.y1 - line.y2);
distance += Math.sqrt(sumOfSquares);
}
return distance;
}

testPreMoves3

Class: jfreerails.network.specifics.MovePrecommitterTest

Documentation

No documentation available

Source Code

public void testPreMoves3() {
PreMove pm = TimeTickPreMove.INSTANCE;
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
// Send a premove to the server.
committer.toServer(pm);
assertEquals(0, committer.uncomitted.size());
assertEquals(1, committer.precomitted.size());
assertEquals(newTime, getTime());
// The server rejects it.
committer.fromServer(PreMoveStatus.failed("failed"));
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
assertEquals(oldtime, getTime());
}

getDisplayMode

Class: jfreerails.launcher.ClientOptionsJPanel

Documentation

No documentation available

Source Code

DisplayMode getDisplayMode() {
if (this.fullScreenButton.isSelected()) {
MyDisplayMode displayMode = ((MyDisplayMode) jList1
.getSelectedValue());
logger.fine("The selected display mode is "
+ displayMode.toString());
return displayMode.displayMode;
}
return null;
}

tryUndoMove

Class: jfreerails.move.TimeTickMove

Documentation

No documentation available

Source Code

public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
GameTime time = w.currentTime();
if (time.equals(newTime)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + newTime + ", found " + time);
}

currentRate

Class: jfreerails.util.FlowRateOutputStream

Documentation

No documentation available

Source Code

public int currentRate() throws IOException {
return (int) (byteSentCumul / 1024D / (nbUsed * (measureInterval / 1000D)));
}

Called Methods

No outgoing method calls

NullTrackPiece

Class: jfreerails.world.track.NullTrackPiece

Documentation

No documentation available

Source Code

private NullTrackPiece() {
}

Called Methods

No outgoing method calls

checkValidity

Class: jfreerails.world.common.Step

Documentation

No documentation available

Source Code

public static boolean checkValidity(ImPoint a, ImPoint b) {
int dx = b.x - a.x;
int dy = b.y - a.y;
return checkValidity(dx, dy);
}

getUpdatedTiles

Class: jfreerails.move.ChangeTrackPieceMove

Documentation

No documentation available

Source Code

public Rectangle getUpdatedTiles() {
// If we are building or removing a station,
// we need to repaint/remove the station radius
// that appears on the map.
int radius = 1;
TrackRule trackRuleAfter = this.trackPieceAfter.getTrackRule();
if (trackRuleAfter.isStation()) {
radius = Math.max(radius, trackRuleAfter.getStationRadius());
}
TrackRule trackRuleBefore = this.trackPieceBefore.getTrackRule();
if (trackRuleBefore.isStation()) {
radius = Math.max(radius, trackRuleBefore.getStationRadius());
}
// Just to be safe.
radius++;
int x;
int y;
int width;
int height;
x = location.x - radius;
y = location.y - radius;
width = radius * 2 + 1;
height = radius * 2 + 1;
return new Rectangle(x, y, width, height);
}

fromInts

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

public static PositionOnTrack[] fromInts(int[] ints) {
PositionOnTrack[] returnValue = new PositionOnTrack[ints.length];
for (int i = 0; i < ints.length; i++) {
PositionOnTrack p = new PositionOnTrack(ints[i]);
returnValue[i] = p;
}
return returnValue;
}

Called Methods

No outgoing method calls

StockTransaction

Class: jfreerails.world.accounts.StockTransaction

Documentation

No documentation available

Source Code

private StockTransaction(int quantity, Money amount) {
super(Transaction.Category.ISSUE_STOCK, -1, quantity, amount);
}

OverviewMapJComponent

Class: jfreerails.client.view.OverviewMapJComponent

Documentation

No documentation available

Source Code

public OverviewMapJComponent(Rectangle r) {
this.setPreferredSize(mapView.getMapSizeInPixels());
mainMapVisRect = r;
}

start_ListOfLegalRoutesAcrossNode

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* A container element start event handling method.
*
* @param meta
* attributes
*/

Source Code

/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_ListOfLegalRoutesAcrossNode(final Attributes meta)
throws SAXException;

Called Methods

No outgoing method calls

MutableSchedule

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public MutableSchedule(ImmutableSchedule s) {
nextScheduledOrder = s.getNextScheduledOrder();
hasPriorityOrders = s.hasPriorityOrders();
for (int i = 0; i < s.getNumOrders(); i++) {
orders.add(s.getOrder(i));
}
}

getLastTickTime

Class: jfreerails.network.specifics.FreerailsClient

Documentation

No documentation available

Source Code

protected long getLastTickTime(){
return moveFork.getLastTickTime();
}

addMapListener

Class: jfreerails.network.specifics.MoveChainFork

Documentation

No documentation available

Source Code

public void addMapListener(WorldMapListener l) {
mapListeners.add(l);
}

Called Methods

No outgoing method calls

playSound

Class: jfreerails.client.common.SoundManager

Documentation

No documentation available

Source Code

public void playSound(String s, int loops) {
if (playSounds) {
try {
if (!samples.containsKey(s)) {
addClip(s);
}
Sample sample = samples.get(s);
Clip clip;
if (voices.size() < maxLines) {
clip = (Clip) mixer.getLine(sample.info);
} else {
clip = voices.removeFirst();
clip.stop();
clip.flush();
clip.close();
}
clip.addLineListener(this);
clip.open(sample.format, sample.audio, 0, sample.size);
clip.loop(loops);
voices.add(clip);
} catch (LineUnavailableException e) {
logger.warning(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}

testTrackPieceLegality

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

public boolean testTrackPieceLegality(int trackTemplateToTest) {
if (trackTemplateToTest != 0) {
return false;
}
return true;
}

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.view.ActiveView

Documentation

No documentation available

Source Code

void setup(ModelRoot modelRoot, ActionRoot ar, RenderersRoot vl,
ActionListener submitButtonCallBack);

Called Methods

No outgoing method calls

emptyInstance

Class: jfreerails.world.station.ConvertedAtStation

Documentation

No documentation available

Source Code

public static ConvertedAtStation emptyInstance(int numberOfCargoTypes) {
int[] convertedTo = emptyConversionArray(numberOfCargoTypes);
return new ConvertedAtStation(convertedTo);
}

ActivityAndTime

Class: jfreerails.world.top.ActivityAndTime

Documentation

No documentation available

Source Code

ActivityAndTime(Activity act, double time) {
this.act = act;
startTime = time;
}

Called Methods

No outgoing method calls

testThatAllTheFieldsDefinedInSKEYAreInstancesOFSKEY

Class: jfreerails.world.top.SKEYTest

Documentation

No documentation available

Source Code

public void testThatAllTheFieldsDefinedInSKEYAreInstancesOFSKEY() {
Field[] fields = SKEY.class.getFields();
for (int i = 0; i < fields.length; i++) {
String name = fields[i].getName();
int modifiers = fields[i].getModifiers();
if (!name.equals("shared")) {
assertTrue("All the fields of SKEY should be static", Modifier
.isStatic(modifiers));
}
assertTrue("All the fields of SKEY should be public", Modifier
.isPublic(modifiers));
assertTrue("All the fields of SKEY should be final", Modifier
.isFinal(modifiers));
try {
if (Modifier.isStatic(modifiers)) {
Object o = fields[i].get(null);
assertTrue("All the fields of SKEY should be instances of"
+ " SKEY", o instanceof SKEY);
}
} catch (IllegalAccessException e) {
assertTrue(false);
}
}
}

Called Methods

No outgoing method calls

initComponents

Class: jfreerails.client.view.TrainOrderJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
gotoIcon = new javax.swing.JLabel();
consistChangeJPanel = new TrainListCellRenderer();
noChangeJLabel = new javax.swing.JLabel();
stationNameJLabel = new javax.swing.JLabel();
ordersJLabel = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
gotoIcon.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/jfreerails/client/graphics/selected_arrow.png")));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridheight = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
add(gotoIcon, gridBagConstraints);
consistChangeJPanel.setLayout(new java.awt.GridBagLayout());
noChangeJLabel.setText("No Change");
consistChangeJPanel.add(noChangeJLabel,
new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
add(consistChangeJPanel, gridBagConstraints);
stationNameJLabel.setText("Some Station");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
add(stationNameJLabel, gridBagConstraints);
ordersJLabel.setText("wait until full / don't wait");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.ipadx = 6;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(0, 6, 0, 5);
add(ordersJLabel, gridBagConstraints);
}// GEN-END:initComponents

Called Methods

No outgoing method calls

getWorld

Class: jfreerails.network.specifics.SimpleServerGameModel

Documentation

No documentation available

Source Code

public World getWorld() {
return w;
}

Called Methods

No outgoing method calls

SimpleMoveReceiver

Class: experimental.SimpleMoveReceiver

Documentation

No documentation available

Source Code

public SimpleMoveReceiver(World w) {
this.w = w;
if (null == w)
throw new NullPointerException();
}

Called Methods

No outgoing method calls

contains

Class: jfreerails.world.common.ImHashSet

Documentation

No documentation available

Source Code

public boolean contains(E e) {
return hashSet.contains(e);
}

Called Methods

No outgoing method calls

currentRateString

Class: jfreerails.util.FlowRateOutputStream

Documentation

No documentation available

Source Code

public String currentRateString() {
double d = (byteSentCumul / 1024D / (nbUsed * (measureInterval / 1000D)));
return decimalFormat.format(d);
}

Called Methods

No outgoing method calls

MapCustomizer

Class: jfreerails.server.MapCustomizer

Documentation

No documentation available

Source Code

public MapCustomizer() {
this(MapFixtureFactory2.getCopy());
}

treasuryStock

Class: jfreerails.controller.FinancialDataGatherer

Documentation

/** Returns the number of stock in the Treasury */

Source Code

/** Returns the number of stock in the Treasury */
public int treasuryStock() {
return stockInRRs[playerID];
}

Called Methods

No outgoing method calls

tryUndoMove

Class: jfreerails.move.AddPlayerMove

Documentation

No documentation available

Source Code

public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int numPlayers = w.getNumberOfPlayers();
Player pp = w.getPlayer(numPlayers - 1);
if (pp.equals(player2add)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("The last player is " + pp.getName()
+ "not " + player2add.getName());
}

engineOnlyJMenuItemActionPerformed

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void engineOnlyJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_engineOnlyJMenuItemActionPerformed
removeAllWagons();
}// GEN-LAST:event_engineOnlyJMenuItemActionPerformed

end_Terrain_Types

Class: jfreerails.server.parser.CargoAndTerrainHandler

Documentation

/**
* A container element end event handling method.
*
*/

Source Code

/**
* A container element end event handling method.
*
*/
public void end_Terrain_Types() throws SAXException;

Called Methods

No outgoing method calls

setUp

Class: jfreerails.controller.MoveTrainPreMove3rdTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
trackBuilder = new TrackMoveProducer(me, world, mr);
stationBuilder = new StationBuilder(me);
// Build track.
stationBuilder
.setStationType(stationBuilder.getTrackTypeID("terminal"));
stationA = new ImPoint(10, 10);
MoveStatus ms0 = trackBuilder.buildTrack(stationA, line1);
assertTrue(ms0.ok);
ms0 = trackBuilder.buildTrack(stationA, line2);
assertTrue(ms0.ok);
ms0 = trackBuilder.buildTrack(stationA, line3);
assertTrue(ms0.ok);
}

nextSpeeds

Class: jfreerails.controller.MoveTrainPreMove

Documentation

No documentation available

Source Code

SpeedAgainstTime nextSpeeds(ReadOnlyWorld w, Step v) {
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
TrainMotion lastMotion = lastMotion(w);
double u = lastMotion.getSpeedAtEnd();
double s = v.getLength();
int wagons = ta.getTrain().getNumberOfWagons();
double a0 = acceleration(wagons);
double topSpeed = topSpeed(wagons);
SpeedAgainstTime newSpeeds;
if (u < topSpeed) {
double t = (topSpeed - u) / a0;
SpeedAgainstTime a = ConstAcc.uat(u, a0, t);
t = s / topSpeed + 1; // Slightly overestimate the time
SpeedAgainstTime b = ConstAcc.uat(topSpeed, 0, t);
newSpeeds = new CompositeSpeedAgainstTime(a, b);
} else {
double t;
t = s / topSpeed + 1; // Slightly overestimate the time
newSpeeds = ConstAcc.uat(topSpeed, 0, t);
}
return newSpeeds;
}

write

Class: jfreerails.util.FlowRateOutputStream

Documentation

No documentation available

Source Code

@Override
public void write(byte[] b, int off, int len) throws IOException {
super.out.write(b, off, len);
totalByteSent += len;
}

Called Methods

No outgoing method calls

getLegalConfigurationsIterator

Class: jfreerails.world.track.LegalTrackConfigurations

Documentation

No documentation available

Source Code

public Iterator<TrackConfiguration> getLegalConfigurationsIterator() {
return legalConfigs.iterator();
}

paintTile

Class: jfreerails.client.renderer.TerrainLayer

Documentation

No documentation available

Source Code

public void paintTile(Graphics g, int tileX, int tileY) {
paintTile(g, new Point(tileX, tileY));
}

Called Methods

  • jfreerails.client.renderer.MapBackgroundRender.TerrainLayer.paintTile (external)

end_Tile

Class: jfreerails.server.parser.CargoAndTerrainHandlerImpl

Documentation

No documentation available

Source Code

public void end_Tile() throws SAXException {
Consumption[] consumes = new Consumption[typeConsumes.size()];
for (int i = 0; i < typeConsumes.size(); i++) {
consumes[i] = typeConsumes.get(i);
}
Production[] produces = new Production[typeProduces.size()];
for (int i = 0; i < typeProduces.size(); i++) {
produces[i] = typeProduces.get(i);
}
Conversion[] converts = new Conversion[typeConverts.size()];
for (int i = 0; i < typeConverts.size(); i++) {
converts[i] = typeConverts.get(i);
}
TileTypeImpl tileType = new TileTypeImpl(tileRGB, tileCategory, tileID,
tileROW, produces, consumes, converts, tileBuildCost);
world.add(SKEY.TERRAIN_TYPES, tileType);
}

getMode

Class: jfreerails.launcher.LauncherPanel1

Documentation

No documentation available

Source Code

int getMode() {
for (int i = 0; i < buttonModels.length; i++) {
if (buttonGroup1.getSelection() == buttonModels[i]) {
return i;
}
}
assert false;
return 0;
}

Called Methods

No outgoing method calls

getPrincipal

Class: jfreerails.move.RemoveItemFromListMove

Documentation

No documentation available

Source Code

public FreerailsPrincipal getPrincipal() {
return principal;
}

Called Methods

No outgoing method calls

isStation

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

public boolean isStation() {
return properties.isStation();
}

itemAdded

Class: jfreerails.client.view.StationInfoJPanel

Documentation

No documentation available

Source Code

public void itemAdded(KEY key, int index, FreerailsPrincipal principal) {
if (modelRoot.getPrincipal().equals(principal))
reactToUpdate(key, index, true);
}

getPoint

Class: jfreerails.world.train.PathOnTiles

Documentation

/**
* Returns the coordinates of the point you would be standing at if you
* walked the specified distance along the path from the start point.
*
* @throws IllegalArgumentException
* if distance < 0
* @throws IllegalArgumentException
* if distance > getLength()
*/

Source Code

/**
* Returns the coordinates of the point you would be standing at if you
* walked the specified distance along the path from the start point.
*
* @throws IllegalArgumentException
* if distance < 0
* @throws IllegalArgumentException
* if distance > getLength()
*/
public ImPoint getPoint(double distance) {
if (0 > distance)
throw new IllegalArgumentException("distance:" + distance + " < 0");
int x = start.x * TILE_DIAMETER + TILE_DIAMETER / 2;
int y = start.y * TILE_DIAMETER + TILE_DIAMETER / 2;
double distanceSoFar = 0;
for (int i = 0; i < vectors.size(); i++) {
Step v = vectors.get(i);
distanceSoFar += v.getLength();
x += v.deltaX * TILE_DIAMETER;
y += v.deltaY * TILE_DIAMETER;
if (distanceSoFar == distance) {
return new ImPoint(x, y);
}
if (distanceSoFar > distance) {
double excess = distanceSoFar - distance;
x -= v.deltaX * TILE_DIAMETER * excess / v.getLength();
y -= v.deltaY * TILE_DIAMETER * excess / v.getLength();
return new ImPoint(x, y);
}
}
throw new IllegalArgumentException("distance > getLength()");
}

updateSupplyRate

Class: jfreerails.controller.CalcCargoSupplyRateAtStation

Documentation

No documentation available

Source Code

private void updateSupplyRate(int type, int rate) {
// loop through supplies vector and increment the cargo values as
// required
for (int n = 0; n < supplies.size(); n++) {
CargoElementObject tempElement = supplies.elementAt(n);
if (tempElement.getType() == type) {
// cargo types are the same, so increment the rate in supply
// with the rate.
tempElement.setRate(tempElement.getRate() + rate);
break; // no need to go through the rest if we've found a match
}
}
}

nextSegment

Class: jfreerails.world.train.SimplePathIteratorImpl

Documentation

No documentation available

Source Code

public void nextSegment(IntLine line) {
if (hasNext()) {
line.x1 = x.get(position);
line.y1 = y.get(position);
line.x2 = x.get(position + 1);
line.y2 = y.get(position + 1);
position++;
} else {
throw new NoSuchElementException();
}
}

setZoom

Class: jfreerails.client.view.SelectStationJPanel

Documentation

/**
* Sets the zoom based on the size of the component and the positions of the
* stations.
*/

Source Code

/**
* Sets the zoom based on the size of the component and the positions of the
* stations.
*/
private void setZoom() {
mapRect = this.getBounds();
Rectangle r = cargoWaitingAndDemandedJPanel1.getBounds();
mapRect.width -= r.width;
int topLeftX = Integer.MAX_VALUE;
int topLeftY = Integer.MAX_VALUE;
int bottomRightX = Integer.MIN_VALUE;
int bottomRightY = Integer.MIN_VALUE;
NonNullElements it = new NonNullElements(KEY.STATIONS, world,
this.principal);
while (it.next()) {
StationModel station = (StationModel) it.getElement();
if (station.x < topLeftX)
topLeftX = station.x;
if (station.y < topLeftY)
topLeftY = station.y;
if (station.x > bottomRightX)
bottomRightX = station.x;
if (station.y > bottomRightY)
bottomRightY = station.y;
}
// Add some padding.
topLeftX -= 10;
topLeftY -= 10;
bottomRightX += 10;
bottomRightY += 10;
int width = bottomRightX - topLeftX;
int height = bottomRightY - topLeftY;
visibleMapTiles = new Rectangle(topLeftX, topLeftY, width, height);
boolean heightConstraintBinds = (visibleMapTiles.getHeight() / visibleMapTiles
.getWidth()) > (mapRect.getHeight() / mapRect.getWidth());
if (heightConstraintBinds) {
scale = mapRect.getHeight() / visibleMapTiles.getHeight();
} else {
scale = mapRect.getWidth() / visibleMapTiles.getWidth();
}
needsUpdating = false;
}

testFindNextVector

Class: jfreerails.controller.MoveTrainPreMove1stTest

Documentation

No documentation available

Source Code

public void testFindNextVector() {
setupLoopOfTrack();
PositionOnTrack pot = PositionOnTrack.createFacing(4, 6, SOUTH_WEST);
ImPoint target = new ImPoint();
Step expected = NORTH_EAST;
assertEquals(expected, MoveTrainPreMove.findNextStep(world, pot,
target));
pot.move(expected);
expected = EAST;
assertEquals(expected, MoveTrainPreMove.findNextStep(world, pot,
target));
pot.move(expected);
expected = SOUTH_EAST;
assertEquals(expected, MoveTrainPreMove.findNextStep(world, pot,
target));
pot.move(expected);
expected = SOUTH;
assertEquals(expected, MoveTrainPreMove.findNextStep(world, pot,
target));
pot.move(expected);
}

getPrincipal

Class: jfreerails.move.TransferCargoAtStationMove

Documentation

/** The player who is getting paid for the delivery. */

Source Code

/** The player who is getting paid for the delivery. */
public FreerailsPrincipal getPrincipal() {
ImList<Move> moves = super.getMoves();
for (int i = CHANGE_AT_STATION_INDEX; i < moves.size(); i++) {
if (moves.get(i) instanceof AddTransactionMove) {
AddTransactionMove move = (AddTransactionMove) moves.get(i);
return move.getPrincipal();
}
}
return Player.NOBODY;
}

testHashCodeAndEquals

Class: jfreerails.util.ListXDTest

Documentation

No documentation available

Source Code

public void testHashCodeAndEquals(){
Integer i = new Integer(5);
Integer ii = new Integer(53);
//1d
list1d.add(i);
Object copy = Utils.cloneBySerialisation(list1d);
assertEquals(copy, list1d);
assertEquals(copy.hashCode(), list1d.hashCode());
list1d.add(ii);
assertFalse(copy.equals(list1d));
//2d
list2d.addD2(0, i);
copy = Utils.cloneBySerialisation(list2d);
assertEquals(copy, list2d);
assertEquals(copy.hashCode(), list2d.hashCode());
list2d.addD2(0, ii);
assertFalse(copy.equals(list2d));
//3d
list3d.addD3(0, 1, i);
copy = Utils.cloneBySerialisation(list3d);
assertEquals(copy, list3d);
assertEquals(copy.hashCode(), list3d.hashCode());
list3d.addD3(0, 1, ii);
assertFalse(copy.equals(list3d));
}

getPassword

Class: jfreerails.network.specifics.LogOnRequest

Documentation

No documentation available

Source Code

public String getPassword() {
return password;
}

Called Methods

No outgoing method calls

setOrderToGoto

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public void setOrderToGoto(int i) {
if (i < 0 || i >= orders.size()) {
throw new IllegalArgumentException(String.valueOf(i));
}
nextScheduledOrder = i;
}

Called Methods

No outgoing method calls

setWorld

Class: jfreerails.network.specifics.ServerGameModel

Documentation

No documentation available

Source Code

void setWorld(World w, String[] passwords);

Called Methods

No outgoing method calls

ListXDDiffs

Class: jfreerails.util.ListXDDiffs

Documentation

No documentation available

Source Code

public ListXDDiffs(SortedMap<ListKey, Object> diffs, Enum listID) {
this.diffs = diffs;
this.listID = listID;
}

Called Methods

No outgoing method calls

getTileViewWithNumber

Class: jfreerails.client.renderer.TileRendererList

Documentation

No documentation available

Source Code

TileRenderer getTileViewWithNumber(int i);

Called Methods

No outgoing method calls

createGameMenu

Class: jfreerails.client.top.GUIComponentFactory

Documentation

No documentation available

Source Code

JMenu createGameMenu();

Called Methods

No outgoing method calls

size

Class: jfreerails.util.List1D

Documentation

No documentation available

Source Code

int size();

Called Methods

No outgoing method calls

testCanStepForward

Class: jfreerails.world.train.PathWalkerImplTest

Documentation

No documentation available

Source Code

/*
* Test for boolean canStepForward()
*/
public void testCanStepForward() {
setup();
assertTrue(pw.canStepForward());
pw.stepForward(500); // The path length is 200;
moveToNextLimit();
assertTrue(!pw.canStepForward());
setup();
assertTrue(pw.canStepForward());
pw.stepForward(10);
assertTrue(pw.canStepForward());
IntLine line = new IntLine();
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertLineEquals(0, 0, 10, 0, line);
assertTrue(!pw.hasNext());
assertTrue(pw.canStepForward());
pw.stepForward(500); // The path length is 200;
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertLineEquals(10, 0, 100, 0, line);
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertLineEquals(100, 0, 100, 100, line);
assertTrue(!pw.canStepForward());
}

PathOnTiles

Class: jfreerails.world.train.PathOnTiles

Documentation

/**
* @throws NullPointerException
* if null == start
* @throws NullPointerException
* if null == vectorsList
* @throws NullPointerException
* if null == vectorsList.get(i) for any i;
*/

Source Code

/**
* @throws NullPointerException
* if null == start
* @throws NullPointerException
* if null == vectorsList
* @throws NullPointerException
* if null == vectorsList.get(i) for any i;
*/
public PathOnTiles(ImPoint start, List<Step> vectorsList) {
if (null == start)
throw new NullPointerException();
vectors = new ImList<Step>(vectorsList);
vectors.checkForNulls();
this.start = start;
}

get

Class: jfreerails.util.List2DImpl

Documentation

No documentation available

Source Code

public T get(int d1, int d2) {
return elementData.get(d1).get(d2);
}

Called Methods

No outgoing method calls

set

Class: jfreerails.util.List3D

Documentation

No documentation available

Source Code

void set(int d1, int d2, int d3, T element);

Called Methods

No outgoing method calls

calcV

Class: jfreerails.world.train.ConstAcc

Documentation

No documentation available

Source Code

public double calcV(double t) {
validateT(t);
return u + a * t;
}

getProperties

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

public TrackRuleProperties getProperties() {
return properties;
}

Called Methods

No outgoing method calls

getWagons

Class: jfreerails.client.view.SelectWagonsJPanel

Documentation

No documentation available

Source Code

public int[] getWagons() {
int[] wagonsArray = new int[wagons.size()];
for (int i = 0; i < wagons.size(); i++) {
Integer type = wagons.get(i);
wagonsArray[i] = type.intValue();
}
return wagonsArray;
}

Called Methods

No outgoing method calls

newStation

Class: jfreerails.controller.AddStationPreMove

Documentation

No documentation available

Source Code

public static AddStationPreMove newStation(ImPoint p, int trackRule,
FreerailsPrincipal principal) {
return new AddStationPreMove(p, trackRule, principal);
}

Called Methods

No outgoing method calls

contains

Class: jfreerails.world.cargo.ImmutableCargoBundle

Documentation

No documentation available

Source Code

public boolean contains(CargoBatch cb) {
for (int i = 0; i < batches.size(); i++) {
if (batches.get(i).equals(cb)) {
return true;
}
}
return false;
}

createOverviewMap

Class: jfreerails.client.top.GUIComponentFactory

Documentation

No documentation available

Source Code

JPanel createOverviewMap();

Called Methods

No outgoing method calls

TerrainInfoJPanel

Class: jfreerails.client.view.TerrainInfoJPanel

Documentation

No documentation available

Source Code

public TerrainInfoJPanel() {
initComponents();
}

setValue

Class: jfreerails.util.FreerailsProgressMonitor

Documentation

No documentation available

Source Code

void setValue(int i);

Called Methods

No outgoing method calls

calcS

Class: jfreerails.world.train.ConstAcc

Documentation

No documentation available

Source Code

public double calcS(double t) {
if(t == finalT) return finalS;
validateT(t);
double ds = u * t + a * t * t / 2;
ds = Math.min(ds, finalS);
return ds;
}

setShowTrainDetailsActionListener

Class: jfreerails.client.view.TrainListJPanel

Documentation

No documentation available

Source Code

void setShowTrainDetailsActionListener(ActionListener l) {
showTrainDetails = l;
}

Called Methods

No outgoing method calls

getTrackPieceIcon

Class: experimental.LineDrawTrackPieceView

Documentation

No documentation available

Source Code

public java.awt.Image getTrackPieceIcon(int trackTemplate) {
return null;
}

Called Methods

No outgoing method calls

contains

Class: jfreerails.client.common.ImageManager

Documentation

No documentation available

Source Code

boolean contains(String relativeFilename);

Called Methods

No outgoing method calls

setAsCurrentManager

Class: jfreerails.client.common.RepaintManagerForActiveRendering

Documentation

No documentation available

Source Code

public static void setAsCurrentManager() {
RepaintManager.setCurrentManager(instance);
}

Called Methods

No outgoing method calls

canAddOrder

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public boolean canAddOrder() {
int max = hasPriorityOrders ? MAXIMUM_NUMBER_OF_ORDER + 1
: MAXIMUM_NUMBER_OF_ORDER;
return max > getNumOrders();
}

toString

Class: jfreerails.move.AddItemToSharedListMove

Documentation

No documentation available

Source Code

@Override
public String toString() {
StringBuffer sb = new StringBuffer(this.getClass().getName());
sb.append("\nlist=");
sb.append(listKey.toString());
sb.append("\n index =");
sb.append(this.index);
sb.append("\n item =");
sb.append(this.item.toString());
return sb.toString();
}

end_TrackType

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void end_TrackType() throws SAXException {
TrackRuleImpl trackRuleImpl = new jfreerails.world.track.TrackRuleImpl(
trackRuleProperties, legalTrackConfigurations,
legalTrackPlacement);
ruleList.add(trackRuleImpl);
legalTrackConfigurations = null;
trackRuleProperties = null;
legalTrackPlacement = null;
}

Called Methods

No outgoing method calls

getCopyOfBundle

Class: jfreerails.controller.DropOffAndPickupCargoMoveGenerator

Documentation

No documentation available

Source Code

private MutableCargoBundle getCopyOfBundle(int id) {
FreerailsSerializable fs = w.get(principal, KEY.CARGO_BUNDLES, id);
ImmutableCargoBundle ibundle = (ImmutableCargoBundle) fs;
return new MutableCargoBundle(ibundle);
}

refreshButtonActionPerformed

Class: jfreerails.client.view.LoadGameJPanel

Documentation

No documentation available

Source Code

private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
Message2Server refreshGames = new RefreshListOfGamesMessage2Server(2);
modelRoot.sendCommand(refreshGames);
}//GEN-LAST:event_refreshButtonActionPerformed

SimpleMoveExecutor

Class: jfreerails.controller.SimpleMoveExecutor

Documentation

No documentation available

Source Code

public SimpleMoveExecutor(World world, int playerID) {
w = world;
Player player = w.getPlayer(playerID);
p = player.getPrincipal();
}

toString

Class: jfreerails.world.train.PathOnTiles

Documentation

No documentation available

Source Code

@Override
public String toString() {
StringBuffer sb = new StringBuffer(getClass().getName());
sb.append("{");
sb.append(start.x);
sb.append(", ");
sb.append(start.y);
for (int i = 0; i < vectors.size(); i++) {
sb.append(", ");
sb.append(vectors.get(i));
}
sb.append("}");
return sb.toString();
}

getTransactionTimeStamp

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

No documentation available

Source Code

GameTime getTransactionTimeStamp(FreerailsPrincipal p, int i);

Called Methods

No outgoing method calls

cancelButtonActionPerformed

Class: jfreerails.client.view.SaveGameJPanel

Documentation

No documentation available

Source Code

private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
close.actionPerformed(evt);
}//GEN-LAST:event_cancelButtonActionPerformed

Called Methods

No outgoing method calls

setImage

Class: jfreerails.client.top.SimpleTileRenderer

Documentation

No documentation available

Source Code

public void setImage(Image i) {
this.i = i;
}

Called Methods

No outgoing method calls

UndoMove

Class: jfreerails.move.UndoMove

Documentation

/**
* @param move
* The move that was undone
*/

Source Code

/**
* @param move
* The move that was undone
*/
public UndoMove(Move move) {
if (move instanceof UndoMove) {
throw new IllegalArgumentException();
}
move2undo = move;
}

Called Methods

No outgoing method calls

drawFPS

Class: jfreerails.client.top.FPScounter

Documentation

No documentation available

Source Code

void drawFPS(Graphics2D g) {
int rectWidth;
int rectHeight;
int rectX;
int rectY;
int positionX = 50;
int positionY = 70;
Color textColor = Color.WHITE;
String[] lines = newFPSstr.split("\n");
rectWidth = 60;
rectHeight = (int) ((fontSize + 1) * 1.2 * lines.length);
rectY = (int) (positionY - fontSize * 1.2);
rectX = positionX;
g.setColor(bgColor);
g.fillRect(rectX, rectY, rectWidth, rectHeight);
g.setColor(textColor);
// g.setFont(font);
for (String s : lines) {
g.drawString(s, positionX, positionY);
positionY += fontSize * 1.2;
}
}

Called Methods

No outgoing method calls

undoMove

Class: jfreerails.move.TimeTickMove

Documentation

No documentation available

Source Code

public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryUndoMove(w, p);
if (status.isOk()) {
w.setTime(oldTime);
}
return status;
}

testGetYearAndMonth

Class: jfreerails.world.common.GameCalenderTest

Documentation

No documentation available

Source Code

public void testGetYearAndMonth() {
GameCalendar gc = new GameCalendar(12, 1900);
assertEquals("Jan 1900", gc.getYearAndMonth(0));
assertEquals("Feb 1900", gc.getYearAndMonth(1));
assertEquals("Mar 1900", gc.getYearAndMonth(2));
assertEquals("Mar 1901", gc.getYearAndMonth(14));
}

sizeD1

Class: jfreerails.util.List2DDiff

Documentation

No documentation available

Source Code

public int sizeD1() {
return super.size();
}

GameLoop

Class: jfreerails.client.top.GameLoop

Documentation

No documentation available

Source Code

public GameLoop(ScreenHandler s) {
screenHandler = s;
model = new GameModel[0];
}

Called Methods

No outgoing method calls

getThreadName

Class: jfreerails.network.InetConnection2Client

Documentation

No documentation available

Source Code

@Override
String getThreadName() {
return "InetConnection2Client";
}

Called Methods

No outgoing method calls

propertyChange

Class: jfreerails.client.view.Unknown

Documentation

No documentation available

Source Code

public void propertyChange(PropertyChangeEvent e) {
if (e.getPropertyName().equals(
StationBuildModel.StationBuildAction.STATION_POSITION_KEY)) {
/* update the renderer pos */
Point p = (Point) e.getNewValue();
stationRadiusRenderer.setPosition(p.x, p.y);
if (stationBuildModel.canBuildStationHere()) {
stationRadiusRenderer
.setBorderColor(StationRadiusRenderer.COLOR_OK);
} else {
stationRadiusRenderer
.setBorderColor(StationRadiusRenderer.COLOR_CANNOT_BUILD);
}
} else if (e.getPropertyName().equals(
StationBuildModel.StationBuildAction.STATION_RADIUS_KEY)) {
Integer radius = (Integer) e.getNewValue();
stationRadiusRenderer.setRadius(radius.intValue());
}
boolean enabled = stationBuildModel.getStationBuildAction()
.isEnabled();
if (buildEnabled != enabled) {
if (enabled) {
mapView.addMouseListener(StationPlacementCursor.this);
mapView.addMouseMotionListener(StationPlacementCursor.this);
stationRadiusRenderer.show();
} else {
stationRadiusRenderer.hide();
mapView.removeMouseListener(StationPlacementCursor.this);
mapView
.removeMouseMotionListener(StationPlacementCursor.this);
}
buildEnabled = enabled;
}
}

testLengtheningTrain

Class: jfreerails.controller.MoveTrainPreMove2ndTest

Documentation

/**
* Tests that when extra wagons are added, the TrainMotion lengthens to
* accommodate them.
*/

Source Code

/**
* Tests that when extra wagons are added, the TrainMotion lengthens to
* accommodate them.
*/
public void testLengtheningTrain() {
// Set the train to add wagons at station2.
ImInts newConsist = new ImInts(0, 0, 0, 0, 0, 0);
TrainOrdersModel order0 = new TrainOrdersModel(2, newConsist, false, false);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
MutableSchedule schedule = new MutableSchedule(ta.getSchedule());
schedule.setOrder(0, order0);
ImmutableSchedule imSchedule = schedule.toImmutableSchedule();
world.set(principal, KEY.TRAIN_SCHEDULES, 0, imSchedule);
assertEquals(0, ta.getSchedule().getOrderToGoto());
// Move the train to the station.
PositionOnTrack pot;
TrainMotion tm;
do {
tm = moveTrain();
pot = tm.getFinalPosition();
} while (pot.getX() < station2Location.x);
assertEquals(station2Location.x, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
TrainModel train = ta.getTrain();
assertEquals(2, train.getNumberOfWagons());
assertTrue(tm.getInitialPosition() >= train.getLength());
tm = moveTrain();
tm = moveTrain();
train = ta.getTrain();
assertEquals(6, ta.getTrain().getNumberOfWagons());
assertTrue(tm.getInitialPosition() >= train.getLength());
}

testRemoveLast

Class: jfreerails.world.common.ImIntsTest

Documentation

No documentation available

Source Code

public void testRemoveLast(){
//Test method does not change original
ImInts original = new ImInts(1,2, 3, 4);
ImInts clone = (ImInts) Utils.cloneBySerialisation(original);
assertEquals(original, clone);
original.removeLast();
assertEquals(original, clone);
ImInts actual, expected;
actual = (new ImInts( 1, 2, 3)).removeLast();
expected = new ImInts(1,2);
assertEquals(expected, actual);
actual = (new ImInts( 1, 2)).removeLast();
expected = new ImInts(1);
assertEquals(expected, actual);
actual = (new ImInts( 1, 2, 4, 3)).removeLast();
expected = new ImInts(1, 2, 4);
assertEquals(expected, actual);
}

disconnect

Class: jfreerails.network.LocalConnection

Documentation

No documentation available

Source Code

public synchronized void disconnect() {
status.close();
}

iterator

Class: jfreerails.world.common.ImHashSet

Documentation

No documentation available

Source Code

public Iterator<E> iterator() {
return new Iterator<E>() {
Iterator<E> it = hashSet.iterator();
public boolean hasNext() {
return it.hasNext();
}
public E next() {
return it.next();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}

Called Methods

No outgoing method calls

currentRateString

Class: jfreerails.util.FlowRateInputStream

Documentation

No documentation available

Source Code

public String currentRateString() {
double d = (byteReceivedCumul / 1024D / (nbUsed * (measureInterval / 1000D)));
return decimalFormat.format(d);
}

Called Methods

No outgoing method calls

handle_Cargo

Class: jfreerails.server.parser.CargoAndTerrainHandler

Documentation

/**
* An empty element event handling method.
*
*/

Source Code

/**
* An empty element event handling method.
*
*/
public void handle_Cargo(final Attributes meta) throws SAXException;

Called Methods

No outgoing method calls

testReverting2OriginalState1

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

public void testReverting2OriginalState1(){
underlying.addD1();
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
diffs.addD1();
assertEquals(3, diffs.sizeD1());
assertEquals(0, diffs.sizeD2(2));
diffs.removeLastD1();
assertEquals(2, diffs.sizeD1());
assertEquals(2, underlying.sizeD1());
assertEquals(0, map.size());
}

getRevenue

Class: jfreerails.move.TransferCargoAtStationMove

Documentation

No documentation available

Source Code

public Money getRevenue() {
ImList<Move> moves = super.getMoves();
long amount = CHANGE_AT_STATION_INDEX;
for (int i = CHANGE_AT_STATION_INDEX; i < moves.size(); i++) {
if (moves.get(i) instanceof AddTransactionMove) {
AddTransactionMove move = (AddTransactionMove) moves.get(i);
DeliverCargoReceipt receipt = (DeliverCargoReceipt) move
.getTransaction();
amount += receipt.deltaCash().getAmount();
}
}
return new Money(amount);
}

getMaximumConsecutivePieces

Class: jfreerails.world.track.LegalTrackConfigurations

Documentation

No documentation available

Source Code

public int getMaximumConsecutivePieces() {
return maximumConsecutivePieces;
}

Called Methods

No outgoing method calls

trackPieceIsLegal

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

public boolean trackPieceIsLegal(TrackConfiguration config) {
return legalConfigurations.trackConfigurationIsLegal(config);
}

canStepForward

Class: jfreerails.world.train.PathWalkerImpl

Documentation

/**
* @return true if we still have more of the current segment, or more
* segments left.
*/

Source Code

/**
* @return true if we still have more of the current segment, or more
* segments left.
*/
public boolean canStepForward() {
if (currentSegment.getLength() > distanceAlongCurrentSegment) {
return true;
} else if (it.hasNext()) {
return true;
} else {
return false;
}
}

addDimension

Class: jfreerails.util.ListXDDiffs

Documentation

No documentation available

Source Code

public int addDimension(int... dim) {
int i = size(dim);
ListKey sizeKeyA = new ListKey(ListKey.Type.EndPoint, listID, dim);
int[] subArray = add2Array(dim, i);
ListKey sizeKeyB = new ListKey(ListKey.Type.EndPoint, listID, subArray);
diffs.put(sizeKeyA, new Integer(i + 1));
diffs.put(sizeKeyB, new Integer(0));
return i;
}

validate

Class: jfreerails.client.top.RenderersRootImpl

Documentation

No documentation available

Source Code

public boolean validate(ReadOnlyWorld w) {
boolean okSoFar = true;
if (!this.tiles.validate(w)) {
okSoFar = false;
}
if (!this.trackPieceViewList.validate(w)) {
okSoFar = false;
}
return okSoFar;
}

initComponents

Class: jfreerails.client.view.TrainSummaryJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
trainNumLabel = new javax.swing.JLabel();
headingLabel = new javax.swing.JLabel();
trainMaintenanceCostLabel = new javax.swing.JLabel();
trainIncomeLabel = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(500, 50));
trainNumLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
trainNumLabel.setText("jLabel1");
trainNumLabel
.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
trainNumLabel.setPreferredSize(new java.awt.Dimension(100, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10);
add(trainNumLabel, gridBagConstraints);
headingLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
headingLabel.setText("jLabel2");
headingLabel
.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
headingLabel.setPreferredSize(new java.awt.Dimension(100, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10);
add(headingLabel, gridBagConstraints);
trainMaintenanceCostLabel
.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
trainMaintenanceCostLabel.setText("jLabel3");
trainMaintenanceCostLabel.setMaximumSize(getMaximumSize());
trainMaintenanceCostLabel.setPreferredSize(new java.awt.Dimension(100,
25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 10);
add(trainMaintenanceCostLabel, gridBagConstraints);
trainIncomeLabel
.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
trainIncomeLabel.setText("jLabel1");
trainIncomeLabel.setPreferredSize(new java.awt.Dimension(100, 25));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0);
add(trainIncomeLabel, gridBagConstraints);
}// GEN-END:initComponents

Called Methods

No outgoing method calls

generateTransactions

Class: jfreerails.move.TrackMoveTransactionsGenerator

Documentation

No documentation available

Source Code

private void generateTransactions() {
transactions.clear();
// For each track type, generate a transaction if any pieces of the type
// have been added or removed.
for (int i = 0; i < trackAdded.length; i++) {
int numberAdded = trackAdded[i];
if (0 != numberAdded) {
TrackRule rule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
Money m = rule.getPrice();
Money total = new Money(-m.getAmount() * numberAdded
/ TrackConfiguration.LENGTH_OF_STRAIGHT_TRACK_PIECE);
Transaction t = new AddItemTransaction(TRACK, i, numberAdded,
total);
transactions.add(t);
}
int numberRemoved = trackRemoved[i];
if (0 != numberRemoved) {
TrackRule rule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
Money m = rule.getPrice();
Money total = new Money((m.getAmount() * numberRemoved)
/ TrackConfiguration.LENGTH_OF_STRAIGHT_TRACK_PIECE);
// You only get half the money back.
total = new Money(total.getAmount() / 2);
Transaction t = new AddItemTransaction(TRACK, i,
-numberRemoved, total);
transactions.add(t);
}
}
if (0 != fixedCostsStations) {
Transaction t = new AddItemTransaction(STATIONS, -1, -1, new Money(
fixedCostsStations));
transactions.add(t);
}
if (0 != fixedCostsBridges) {
Transaction t = new AddItemTransaction(BRIDGES, -1, -1, new Money(
fixedCostsBridges));
transactions.add(t);
}
}

getScreenHandler

Class: jfreerails.launcher.GUIClient

Documentation

No documentation available

Source Code

public ScreenHandler getScreenHandler() {
return screenHandler;
}

Called Methods

No outgoing method calls

paintTile

Class: jfreerails.client.renderer.Unknown

Documentation

No documentation available

Source Code

public void paintTile(Graphics g, int tileX, int tileY) {
}

Called Methods

No outgoing method calls

paintRectangleOfTiles

Class: jfreerails.client.renderer.TerrainLayer

Documentation

/**
* Paints a rectangle of tiles on the supplied graphics context.
*
* @param g
* The graphics context.
* @param tilesToPaint
* The rectangle, measured in tiles, to paint.
*/

Source Code

/**
* Paints a rectangle of tiles on the supplied graphics context.
*
* @param g
* The graphics context.
* @param tilesToPaint
* The rectangle, measured in tiles, to paint.
*/
public void paintRectangleOfTiles(Graphics g, Rectangle tilesToPaint) {
Point tile = new Point();
for (tile.x = tilesToPaint.x; tile.x < (tilesToPaint.x + tilesToPaint.width); tile.x++) {
for (tile.y = tilesToPaint.y; tile.y < (tilesToPaint.y + tilesToPaint.height); tile.y++) {
terrainLayer.paintTile(g, tile);
}
}
}

Called Methods

  • jfreerails.client.renderer.MapBackgroundRender.TerrainLayer.paintTile (external)

getT

Class: jfreerails.world.train.ConstAcc

Documentation

No documentation available

Source Code

public double getT() {
return finalT;
}

Called Methods

No outgoing method calls

open

Class: jfreerails.network.SynchronizedFlag

Documentation

No documentation available

Source Code

public synchronized void open() {
this.isOpen = true;
notifyAll();
}

Called Methods

No outgoing method calls

getQuantity

Class: jfreerails.world.accounts.DeliverCargoReceipt

Documentation

No documentation available

Source Code

public int getQuantity() {
return quantity;
}

Called Methods

No outgoing method calls

getBaseInterestRate

Class: jfreerails.world.accounts.EconomicClimate

Documentation

No documentation available

Source Code

public int getBaseInterestRate() {
return baseInterestRate;
}

Called Methods

No outgoing method calls

from9bitTemplate

Class: jfreerails.world.track.TrackConfiguration

Documentation

No documentation available

Source Code

public static TrackConfiguration from9bitTemplate(int i) {
return flatTrackConfigurations.get(i);
}

Called Methods

No outgoing method calls

findRuleID

Class: jfreerails.move.ChangeTrackPieceCompositeMove

Documentation

No documentation available

Source Code

public static int findRuleID(TrackRule r, ReadOnlyWorld w) {
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
Object o = w.get(SKEY.TRACK_RULES, i);
if (r.equals(o)) {
return i;
}
}
throw new IllegalStateException();
}

getRowID

Class: jfreerails.world.top.NonNullElements

Documentation

No documentation available

Source Code

public int getRowID() {
return row;
}

Called Methods

No outgoing method calls

testCanAddToHead

Class: jfreerails.world.train.TrainPositionOnMapTest

Documentation

No documentation available

Source Code

public void testCanAddToHead() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
b = TrainPositionOnMap.createInstance(new int[] { 20, 30 }, new int[] {
22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 30, 40 }, new int[] {
33, 44 });
assertTrue(b.canAddToHead(a));
assertTrue(!a.canAddToHead(b));
assertTrue(c.canAddToHead(b));
assertTrue(!b.canAddToHead(c));
assertTrue(!c.canAddToHead(a));
assertTrue(!a.canAddToHead(c));
}

scanAdjacentTiles

Class: jfreerails.controller.CalcCargoSupplyRateAtStation

Documentation

No documentation available

Source Code

public Vector<CargoElementObject> scanAdjacentTiles() {
int stationDiameter = stationRadius * 2 + 1;
Rectangle stationRadiusRect = new Rectangle(x - stationRadius, y
- stationRadius, stationDiameter, stationDiameter);
Rectangle mapRect = new Rectangle(0, 0, w.getMapWidth(), w
.getMapHeight());
Rectangle tiles2scan = stationRadiusRect.intersection(mapRect);
logger.fine("stationRadiusRect=" + stationRadiusRect);
logger.fine("mapRect=" + mapRect);
logger.fine("tiles2scan=" + tiles2scan);
// Look at the terrain type of each tile and retrieve the cargo
// supplied.
// The station radius determines how many tiles each side we look at.
for (int i = tiles2scan.x; i < (tiles2scan.x + tiles2scan.width); i++) {
for (int j = tiles2scan.y; j < (tiles2scan.y + tiles2scan.height); j++) {
incrementSupplyAndDemand(i, j);
}
}
// return the supplied cargo rates
return supplies;
}

endAtSegmentEnd

Class: jfreerails.world.train.PathWalkerImpl

Documentation

No documentation available

Source Code

private void endAtSegmentEnd(IntLine line,
double remainingDistanceAlongCurrentSegment) {
line.x2 = this.currentSegment.x2;
line.y2 = this.currentSegment.y2;
this.distanceOfThisStepRemaining -= remainingDistanceAlongCurrentSegment;
distanceAlongCurrentSegment = this.currentSegment.getLength();
}

getScaledImage

Class: jfreerails.client.renderer.MyRenderersRoot

Documentation

No documentation available

Source Code

@Override
public Image getScaledImage(String relativeFilename, int height) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}

Called Methods

No outgoing method calls

getCargoAtStation

Class: jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest

Documentation

/**
* Retrieves the cargo bundle that is waiting at the station from the world
* object.
*/

Source Code

/**
* Retrieves the cargo bundle that is waiting at the station from the world
* object.
*/
private ImmutableCargoBundle getCargoAtStation() {
StationModel station = (StationModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
0);
ImmutableCargoBundle cargoAtStation = (ImmutableCargoBundle) w.get(
MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES,
station.getCargoBundleID());
return cargoAtStation;
}

TrainMotionExpt

Class: experimental.TrainMotionExpt

Documentation

No documentation available

Source Code

public TrainMotionExpt() {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
TrackMoveProducer producer = new TrackMoveProducer(me, world, mr);
Step[] trackPath = { EAST, SOUTH_EAST, SOUTH, SOUTH_WEST, WEST,
NORTH_WEST, NORTH, NORTH_EAST };
ImPoint from = new ImPoint(5, 5);
MoveStatus ms = producer.buildTrack(from, trackPath);
if (!ms.ok)
throw new IllegalStateException(ms.message);
TrainOrdersModel[] orders = {};
ImmutableSchedule is = new ImmutableSchedule(orders, -1, false);
AddTrainPreMove addTrain = new AddTrainPreMove(0, new ImInts(), from,
principal, is);
Move m = addTrain.generateMove(world);
ms = m.doMove(world, principal);
if (!ms.ok)
throw new IllegalStateException(ms.message);
startTime = System.currentTimeMillis();
}

get

Class: jfreerails.util.List1DDiff

Documentation

No documentation available

Source Code

public T get(int i) {
return get(new int[] { i });
}

getTrackPieceIcon

Class: jfreerails.client.renderer.TrackPieceRendererImpl

Documentation

No documentation available

Source Code

public Image getTrackPieceIcon(int trackTemplate) {
if ((trackTemplate > 511) || (trackTemplate < 0)) {
throw new java.lang.IllegalArgumentException("trackTemplate = "
+ trackTemplate + ", it should be in the range 0-511");
}
return trackPieceIcons[trackTemplate];
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.station.PlannedTrain

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof PlannedTrain))
return false;
final PlannedTrain productionAtEngineShop = (PlannedTrain) o;
if (engineType != productionAtEngineShop.engineType)
return false;
if (!wagonTypes.equals(productionAtEngineShop.wagonTypes))
return false;
return true;
}

refreshBackground

Class: jfreerails.client.renderer.BufferedTiledBackgroundRenderer

Documentation

No documentation available

Source Code

private void refreshBackground() {
paintBufferRectangle(0, 0, bufferRect.width, bufferRect.height);
}

failed

Class: jfreerails.controller.PreMoveStatus

Documentation

No documentation available

Source Code

public static PreMoveStatus failed(String reason) {
return new PreMoveStatus(MoveStatus.moveFailed(reason));
}

getUnderlyingSize

Class: jfreerails.util.ListXDDiffs

Documentation

/**
* Returns the size of the underlying list at the specified dimension or -1
* if the underlying list does not have the specified dimension.
*/

Source Code

/**
* Returns the size of the underlying list at the specified dimension or -1
* if the underlying list does not have the specified dimension.
*/
abstract int getUnderlyingSize(int... dim);

Called Methods

No outgoing method calls

SynchronizedEventQueue

Class: jfreerails.client.top.SynchronizedEventQueue

Documentation

/** Enforce singleton property. */

Source Code

/** Enforce singleton property. */
private SynchronizedEventQueue() {
}

Called Methods

No outgoing method calls

gotoLastActivity

Class: jfreerails.world.common.ActivityIterator

Documentation

No documentation available

Source Code

void gotoLastActivity();

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.view.StationInfoJPanel

Documentation

No documentation available

Source Code

public void setup(ModelRoot mr, RenderersRoot vl, Action al) {
this.wi = new NonNullElements(KEY.STATIONS, mr.getWorld(), mr
.getPrincipal());
addComponentListener(componentListener);
this.w = mr.getWorld();
this.modelRoot = mr;
this.close.addActionListener(al);
}

close

Class: jfreerails.util.FlowRateOutputStream

Documentation

No documentation available

Source Code

@Override
public void close() throws IOException {
closeRequested = true;
super.close();
do {
try {
Thread.currentThread();
Thread.sleep(50L);
} catch (InterruptedException interruptedexception) {
}
} while (running);
logger.info(String.valueOf(String.valueOf((new StringBuffer("Stream "))
.append(streamName).append(": Open duration = ").append(
(System.currentTimeMillis() - openTimeMillis) / 1000D)
.append(", Byte sent = ").append(totalByteSent).append(" (")
.append((int) (totalByteSent / 1024D)).append(
" Ko), overall flow rate = ").append(
overallRateString()).append(" Ko/s"))));
}

addStationJButtonActionPerformed

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void addStationJButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_addStationJButtonActionPerformed
MutableSchedule s = getSchedule();
try {
int newOrderNumber = s.addOrder(new TrainOrdersModel(
getFirstStationID(), null, false, false)); // TODO fix bug
showSelectStation(s, newOrderNumber);
} catch (NoSuchElementException e) {
logger
.warning("No stations exist so can't add station to schedule!");
}
}// GEN-LAST:event_addStationJButtonActionPerformed

end_Terrain_Types

Class: jfreerails.server.parser.CargoAndTerrainHandlerImpl

Documentation

No documentation available

Source Code

public void end_Terrain_Types() throws SAXException {
// no need to do anything here.
}

Called Methods

No outgoing method calls

initComponents

Class: jfreerails.client.view.SaveGameJPanel

Documentation

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/

Source Code

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jLabel1 = new javax.swing.JLabel();
fileNameTextField = new javax.swing.JTextField();
oKButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
jLabel1.setText("Please enter a name for the save game.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(jLabel1, gridBagConstraints);
fileNameTextField.setText("savegame");
fileNameTextField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
fileNameTextFieldActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(fileNameTextField, gridBagConstraints);
oKButton.setText("OK");
oKButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
oKButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(oKButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(cancelButton, gridBagConstraints);
}

testLogon

Class: jfreerails.network.specifics.FreerailsGameServerTest

Documentation

No documentation available

Source Code

public void testLogon() {
LogOnResponse response;
/* Test 1 */
LogOnRequest request1 = new LogOnRequest("Name", "password");
response = server.logon(request1);
assertTrue("Simple case, should go through.", response.isSuccessful());
assertEquals("1st logon is player 0", 0, response.getPlayerID());
/* Test 2 */
LogOnRequest request2 = new LogOnRequest("Name2", "password2");
response = server.logon(request2);
assertTrue("Simple case, should go through.", response.isSuccessful());
assertEquals("2nd logon is player 1", 1, response.getPlayerID());
/* Test 3: When player is already logged on. */
LogOnRequest request3 = new LogOnRequest("Name", "password");
response = server.logon(request3);
assertFalse("Player is already logged on.", response.isSuccessful());
/* Test 4: When new logons are not allowed. */
server.setNewPlayersAllowed(false);
LogOnRequest request4 = new LogOnRequest("Name4", "password4");
response = server.logon(request4);
assertFalse("New logons are not allowed.", response.isSuccessful());
/* Test 5: When the player has logged off, then tries to log on. */
server.logoff(0);
LogOnRequest request5 = request1;
response = server.logon(request5);
assertTrue("Player 0 has logged off, so should succeed.", response
.isSuccessful());
assertEquals("Should keep the same player id", 0, response
.getPlayerID());
/*
* Test 6: When the player has logged off, then tries to log on with
* wrong password.
*/
server.logoff(0);
LogOnRequest request6 = new LogOnRequest("Name", "batman");
response = server.logon(request6);
assertFalse("Player 0 has logged off, but the password is wrong.",
response.isSuccessful());
}

getEngineType

Class: jfreerails.world.station.PlannedTrain

Documentation

No documentation available

Source Code

public int getEngineType() {
return engineType;
}

Called Methods

No outgoing method calls

GrowableBase

Class: jfreerails.util.GrowableBase

Documentation

/**
* Constructor with full specification.
*
* @param size
* number of elements in initial array
* @param growth
* maximum size increment for growing array
* @param type
* array element type
*/

Source Code

/**
* Constructor with full specification.
*
* @param size
* number of elements in initial array
* @param growth
* maximum size increment for growing array
* @param type
* array element type
*/
public GrowableBase(int size, int growth, Class type) {
Object array = Array.newInstance(type, size);
countLimit = size;
maximumGrowth = growth;
setArray(array);
}

getNaturalNumber

Class: jfreerails.world.top.WorldIterator

Documentation

/**
* Returns the number of the row where the cursor is (the first row is 1).
*/

Source Code

/**
* Returns the number of the row where the cursor is (the first row is 1).
*/
int getNaturalNumber();

Called Methods

No outgoing method calls

instantiateOneOfEach

Class: jfreerails.util.ClassLocater

Documentation

/**
* Finds all classes that implement or extend a given class name, and
* instantiates precisely one copy of each
*
* @param className
* fully qualified class or interface to find subclasses of, e.g.
* "java.lang.String"
* @param skipPrefixes
* prefixes of fully qualified packages or class names to
* completely ignore (i.e. not bother to check), making it
* faster, e.g. "java.", "com.sun"
* @return instantiated objects
*/

Source Code

/**
* Finds all classes that implement or extend a given class name, and
* instantiates precisely one copy of each
*
* @param className
* fully qualified class or interface to find subclasses of, e.g.
* "java.lang.String"
* @param skipPrefixes
* prefixes of fully qualified packages or class names to
* completely ignore (i.e. not bother to check), making it
* faster, e.g. "java.", "com.sun"
* @return instantiated objects
*/
public static List instantiateOneOfEach(String className,
String[] skipPrefixes) {
Class[] classes = null;
LinkedList<Object> instances = new LinkedList<Object>();
try {
ClassLocater locater = new ClassLocater();
for (int i = 0; i < skipPrefixes.length; i++) {
locater.addSkipPrefix(skipPrefixes[i]);
}
classes = locater.getSubclassesOf(Class.forName(className));
logger.info("Found " + classes.length + " classes that implement "
+ className + "...");
if (logger.getLevel().equals(Level.FINE))
for (int i = 0; i < classes.length; i++) {
logger.fine("Found " + classes[i].getName()
+ " that implements " + className + "...");
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Attempting to find " + className
+ " implementers", e);
}
// Iterate through all, instantiating them
logger.fine("Instantiating each class");
for (int i = 0; i < classes.length; i++) {
try {
Object o = classes[i].newInstance();
instances.add(o);
} catch (Throwable e) {
logger.log(Level.SEVERE, "Failed to process: "
+ classes[i].getName(), e);
}
}
return instances;
}

main

Class: jfreerails.world.train.PathWalkerImplTest

Documentation

No documentation available

Source Code

public static void main(String[] args) {
junit.textui.TestRunner.run(PathWalkerImplTest.class);
}

Called Methods

No outgoing method calls

getRule

Class: jfreerails.controller.BuildTrackStrategy

Documentation

No documentation available

Source Code

public int getRule(int terrainType) {
return rules[terrainType];
}

Called Methods

No outgoing method calls

testAddingNullElement

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

public void testAddingNullElement(){
underlying.addD1();
underlying.addD2(0, null);
diffs.removeLastD2(0);
diffs.addD2(0, new Integer(1));
assertEquals(1, map.size());
diffs.removeLastD2(0);
diffs.addD2(0, null);
assertEquals(0, map.size());
diffs.addD2(0, null);
}

getID

Class: jfreerails.world.common.Step

Documentation

/**
* @return a number representing the compass point this vector indicates,
* with 0 representing North, 1 NorthEast, 2 East and so on.
*/

Source Code

/**
* @return a number representing the compass point this vector indicates,
* with 0 representing North, 1 NorthEast, 2 East and so on.
*/
public int getID() {
int i = 0;
while (this != list[i]) {
i++;
}
return i;
}

Called Methods

No outgoing method calls

getBuildCost

Class: jfreerails.world.terrain.NullTerrainType

Documentation

No documentation available

Source Code

public Money getBuildCost() {
return new Money(0);
}

Called Methods

No outgoing method calls

pathAsVectors

Class: jfreerails.controller.TrackPathFinder

Documentation

No documentation available

Source Code

public Step[] pathAsVectors() {
IntArray path = pathFinder.retrievePath();
int size = path.size();
Step[] vectors = new Step[size];
PositionOnTrack progress = new PositionOnTrack();
int x = startPoint.x;
int y = startPoint.y;
for (int i = 0; i < size; i++) {
progress.setValuesFromInt(path.get(i));
int x2 = progress.getX();
int y2 = progress.getY();
vectors[i] = Step.getInstance(x2 - x, y2 - y);
x = x2;
y = y2;
}
return vectors;
}

compareTo

Class: jfreerails.client.view.PlayerDetails

Documentation

No documentation available

Source Code

public int compareTo(PlayerDetails test) {
long l = test.networth.getAmount() - networth.getAmount();
return (int) l;
}

testReadFromServer

Class: jfreerails.network.LocalConnectionTest

Documentation

No documentation available

Source Code

public void testReadFromServer() {
FreerailsSerializable[] objectsRead;
try {
objectsRead = localConnection.readFromServer();
assertNotNull(objectsRead);
assertTrue(Arrays.equals(EmptyArray, objectsRead));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}

testSortedMap

Class: jfreerails.util.List1DDiffsTest

Documentation

No documentation available

Source Code

public void testSortedMap(){
ListKey elementKey1 = new ListKey(ListKey.Type.Element, test.test, 0);
ListKey elementKey2 = new ListKey(ListKey.Type.Element, test.test, 1);
ListKey elementKey3 = new ListKey(ListKey.Type.Element, test.test, 0);
map.put(elementKey1, String.valueOf(1));
assertFalse(map.containsKey(elementKey2));
assertTrue(map.containsKey(elementKey1));
assertTrue(map.containsKey(elementKey3));
}

Called Methods

No outgoing method calls

loadText

Class: jfreerails.client.view.BrokerJFrame

Documentation

/** Load the help text from file. */

Source Code

/** Load the help text from file. */
String loadText(final URL htmlUrl) {
try {
InputStream in = htmlUrl.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
new DataInputStream(in)));
String line;
String text = "";
while ((line = br.readLine()) != null) {
text = text + line;
}
return text;
} catch (Exception e) {
e.printStackTrace();
logger.warning(htmlUrl.toString());
return "Couldn't read: " + htmlUrl;
}
}

Called Methods

No outgoing method calls

testFindingPath

Class: jfreerails.controller.MoveTrainPreMove3rdTest

Documentation

No documentation available

Source Code

public void testFindingPath(){
findPath2Target(new ImPoint(14, 7), line1);
findPath2Target(new ImPoint(9, 13), line2);
findPath2Target(new ImPoint(9, 13), line2);
}

newGame

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public void newGame(String mapName, int numAI) {
for (int i = 0; i < numAI; ++i) {
NameAndPassword aiPlayer = new NameAndPassword("AI" + i, null);
players.add(aiPlayer);
}
this.newGame(mapName);
}

removeFromHead

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public TrainPositionOnMap removeFromHead(TrainPositionOnMap b) {
if (headsAreEqual(this, b)) {
int newLength = this.getLength() - b.getLength() + 2;
int[] newXpoints = new int[newLength];
int[] newYpoints = new int[newLength];
int bLength = b.getLength();
// copy head from b
int bHeadPosition = b.getLength() - 1;
newXpoints[0] = b.getX(bHeadPosition);
newYpoints[0] = b.getY(bHeadPosition);
// Copy rest from this
for (int i = 1; i < newLength; i++) {
int position = bLength + i - 2;
newXpoints[i] = this.getX(position);
newYpoints[i] = this.getY(position);
}
return new TrainPositionOnMap(newXpoints, newYpoints, speed,
acceleration, activity);
}
throw new IllegalArgumentException();
}

equals

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (null == o) {
return false;
}
if (o == this) {
return true;
}
if (o instanceof TrainPositionOnMap) {
TrainPositionOnMap other = (TrainPositionOnMap) o;
int thisLength = this.getLength();
int otherLength = other.getLength();
if (thisLength == otherLength) {
FreerailsPathIterator path1;
FreerailsPathIterator path2;
IntLine line1 = new IntLine();
IntLine line2 = new IntLine();
path1 = other.path();
path2 = this.path();
while (path1.hasNext() && path2.hasNext()) {
path1.nextSegment(line1);
path2.nextSegment(line2);
if (line1.x1 != line2.x1 || line1.y1 != line2.y1
|| line1.x2 != line2.x2 || line1.y2 != line2.y2) {
return false;
}
}
if (path1.hasNext() || path2.hasNext()) {
return false;
}
return true;
}
return false;
}
return false;
}

getCategory

Class: jfreerails.world.accounts.Transaction

Documentation

No documentation available

Source Code

Category getCategory();

Called Methods

No outgoing method calls

getKeyID

Class: jfreerails.world.top.ITEM

Documentation

No documentation available

Source Code

int getKeyID() {
return keyNumber;
}

Called Methods

No outgoing method calls

getMove

Class: jfreerails.move.CompositeMove

Documentation

/**
* This method lets sub classes look at the moves.
*/

Source Code

/**
* This method lets sub classes look at the moves.
*/
final Move getMove(int i) {
return moves.get(i);
}

getState

Class: jfreerails.world.top.TestActivity

Documentation

No documentation available

Source Code

public FreerailsSerializable getState(double dt) {
return new TestState((int) dt);
}

Called Methods

No outgoing method calls

println

Class: jfreerails.client.view.MapViewJComponentConcrete

Documentation

No documentation available

Source Code

private void println(String s) {
StringTokenizer st = new StringTokenizer(s, "\n");
this.userMessage = new String[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
userMessage[i] = st.nextToken();
i++;
}
// Display the message for 5 seconds.
displayMessageUntil = System.currentTimeMillis() + 1000 * 5;
}

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.view.HtmlJPanel

Documentation

No documentation available

Source Code

public void setup(ModelRoot m, RenderersRoot vl,
Action closeAction) {
this.done.setAction(closeAction);
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.train.TrainOrdersModel

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = (waitUntilFull ? 1 : 0);
result = 29 * result + (autoConsist ? 1 : 0);
result = 29 * result + (consist != null ? consist.hashCode() : 0);
result = 29 * result + stationId;
return result;
}

testPickUpAndDropOffSameCargoType

Class: jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest

Documentation

/**
* Tests that a train drops off any cargo before picking up cargo.
*/

Source Code

/**
* Tests that a train drops off any cargo before picking up cargo.
*/
public void testPickUpAndDropOffSameCargoType() {
// Set cargo at station and on train.
setCargoOnTrain(this.cargoType0FromStation2, 120);
setCargoAtStation(this.cargoType0FromStation0, 200);
// Set station to demand cargo 0.
StationModel station = (StationModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
0);
Demand4Cargo demand = new Demand4Cargo(new boolean[] { true,
false, false, false });
station = new StationModel(station, demand);
w.set(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, 0, station);
assertTrue(station.getDemand().isCargoDemanded(0));
stopAtStation();
MutableCargoBundle expectedOnTrain = new MutableCargoBundle();
expectedOnTrain.setAmount(this.cargoType0FromStation0, 120);
MutableCargoBundle expectedAtStation = new MutableCargoBundle();
expectedAtStation.setAmount(this.cargoType0FromStation0, 80);
assertEquals(expectedOnTrain.toImmutableCargoBundle(),
getCargoOnTrain());
assertEquals(expectedAtStation.toImmutableCargoBundle(),
getCargoAtStation());
}

getDistance

Class: jfreerails.controller.CalcNearestCity

Documentation

No documentation available

Source Code

private double getDistance(int cityX, int cityY) {
double distance = 0;
double a = (this.x - cityX) * (this.x - cityX);
double b = (this.y - cityY) * (this.y - cityY);
distance = Math.sqrt(a + b);
return distance;
}

Called Methods

No outgoing method calls

compareTo

Class: jfreerails.world.track.TrackRuleImpl

Documentation

/**
* If the specified object is a track rule, comparison is by category then
* price.
*/

Source Code

/**
* If the specified object is a track rule, comparison is by category then
* price.
*/
public int compareTo(TrackRule otherRule) {
int comp = otherRule.getCategory().compareTo(getCategory());
if (comp != 0) {
return -comp;
}
long dPrice = this.properties.getPrice().getAmount()
- otherRule.getPrice().getAmount();
return (int) dPrice;
}

equals

Class: jfreerails.world.accounts.TransactionAndTimeStamp

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TransactionAndTimeStamp))
return false;
final TransactionAndTimeStamp transactionAndTimeStamp = (TransactionAndTimeStamp) o;
if (!t.equals(transactionAndTimeStamp.t))
return false;
if (!timeStamp.equals(transactionAndTimeStamp.timeStamp))
return false;
return true;
}

startServer

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public static FreerailsGameServer startServer(SavedGamesManager gamesManager) {
FreerailsGameServer server = new FreerailsGameServer(gamesManager);
Thread t = new Thread(server);
t.start();
try {
/* Wait for the server to start before returning. */
synchronized (server.status) {
server.status.wait();
}
return server;
} catch (InterruptedException e) {
e.printStackTrace();
throw new IllegalStateException();
}
}

Called Methods

No outgoing method calls

startBlock

Class: experimental.GenerateDependenciesXmlAndHtml

Documentation

No documentation available

Source Code

private void startBlock(String blockName) {
assert started;
assert !startedBlock;
startedBlock = true;
htmlWriter.write("<h2>" + blockName + "</h2>");
xmlWriter
.write("\n\t\t<!-- Setup the directory where the legal dependencies are stored -->\n");
xmlWriter.write("\t\t<delete dir=\"dependencies\" />\n");
xmlWriter.write("\t\t<mkdir dir=\"dependencies\" />\n");
}

Called Methods

No outgoing method calls

tearDown

Class: jfreerails.controller.PathOnTrackFinderTest

Documentation

No documentation available

Source Code

@Override
protected void tearDown() throws Exception {
super.tearDown();
}

Called Methods

No outgoing method calls

testHit5

Class: jfreerails.client.renderer.TrainRendererTest

Documentation

No documentation available

Source Code

@Test
public void testHit5() {
Point wagonCenter = new Point(100, 100);
Point mouseClick = new Point(96, 100);
boolean hit = isHit(wagonCenter, mouseClick, Step.NORTH);
assertTrue(hit);
}

actionPerformed

Class: jfreerails.client.view.Unknown

Documentation

No documentation available

Source Code

public void actionPerformed(ActionEvent arg0) {
showSelectWagons();
}

setTotalsArrayLength

Class: jfreerails.world.top.ItemsTransactionAggregator

Documentation

No documentation available

Source Code

@Override
protected void setTotalsArrayLength(int length) {
super.setTotalsArrayLength(length);
quantities = new int[length];
quantityRunningTotal = 0;
}

setup

Class: jfreerails.client.top.UserInputOnMapController

Documentation

No documentation available

Source Code

public void setup(MapViewJComponent mv, TrackMoveProducer trackBuilder,
StationTypesPopup stPopup, ModelRoot mr, DialogueBoxController dbc,
FreerailsCursor cursor, BuildTrackController buildTrack, TrainRenderer trainRenderer) {
this.dialogueBoxController = dbc;
this.mapView = mv;
this.stationTypesPopup = stPopup;
this.trackBuilder = trackBuilder;
this.buildTrack = buildTrack;
this.trainRenderer = trainRenderer;
buildIndustryJPopupMenu.setup(mr, null, null);
/*
* We attempt to remove listeners before adding them to prevent them
* being added several times.
*/
mapView.removeMouseListener(mouseInputAdapter);
mapView.addMouseListener(mouseInputAdapter);
mapView.removeMouseMotionListener(mouseInputAdapter);
mapView.addMouseMotionListener(mouseInputAdapter);
mapView.removeKeyListener(this);
mapView.addKeyListener(this);
}

endDocument

Class: jfreerails.server.parser.Track_TilesParser

Documentation

No documentation available

Source Code

public void endDocument() throws SAXException {
}

Called Methods

No outgoing method calls

setCursorMessage

Class: jfreerails.client.top.UserInputOnMapController

Documentation

No documentation available

Source Code

private void setCursorMessage(String s) {
modelRoot.setProperty(Property.CURSOR_MESSAGE, s);
}

testAdd

Class: jfreerails.world.track.TrackConfigurationTest

Documentation

No documentation available

Source Code

public void testAdd() {
TrackConfiguration a = TrackConfiguration.getFlatInstance("000010000");
TrackConfiguration b = TrackConfiguration.add(a, Step.NORTH_WEST);
assertEquals(TrackConfiguration.getFlatInstance("100010000"), b);
assertEquals(false, a == b);
}

testGetListDiffs

Class: jfreerails.world.top.WorldDiffsTest

Documentation

No documentation available

Source Code

public void testGetListDiffs(){
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
WorldDiffs diffs = new WorldDiffs(underlyingWorld);
CityModel city = new CityModel("Bristol", 10, 4);
diffs.add(SKEY.CITIES, city);
Iterator<ListKey> it = diffs.getListDiffs();
@SuppressWarnings("unused")
ListKey lk1 = it.next();
ListKey lk2 = it.next();
assertFalse(it.hasNext());
ListKey expected = new ListKey(Element, SHARED_LISTS, SKEY.CITIES.getKeyID(), 0);
assertEquals(expected, lk2);
}

hashCode

Class: jfreerails.world.train.EngineType

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = powerAtDrawbar;
result = 29 * result + engineTypeName.hashCode();
result = 29 * result + price.hashCode();
result = 29 * result + maintenance.hashCode();
result = 29 * result + maxSpeed;
return result;
}

CompositeMove

Class: jfreerails.move.CompositeMove

Documentation

No documentation available

Source Code

public CompositeMove(List<Move> movesArrayList) {
moves = new ImList<Move>(movesArrayList);
}

Called Methods

No outgoing method calls

AbstractInetConnection

Class: jfreerails.network.AbstractInetConnection

Documentation

No documentation available

Source Code

public AbstractInetConnection(String ip, int port) throws IOException {
inetConnection = new InetConnection(ip, port);
open();
}

getStartTime

Class: jfreerails.world.top.ActivityIteratorImpl

Documentation

No documentation available

Source Code

public double getStartTime() {
return ant.startTime;
}

Called Methods

No outgoing method calls

getTrackGraphicID

Class: jfreerails.world.track.TrackPiece

Documentation

No documentation available

Source Code

int getTrackGraphicID();

Called Methods

No outgoing method calls

getNumber

Class: jfreerails.world.cargo.Categories

Documentation

No documentation available

Source Code

public int getNumber() {
return nr;
}

Called Methods

No outgoing method calls

itemRemoved

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void itemRemoved(KEY key, int index, FreerailsPrincipal principal) {
// do nothing
}

Called Methods

No outgoing method calls

getServerDetails

Class: jfreerails.network.Connection2Server

Documentation

No documentation available

Source Code

String getServerDetails();

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.view.ActionRoot

Documentation

/**
* Call this method when a new game is started or a game is loaded.
*/

Source Code

/**
* Call this method when a new game is started or a game is loaded.
*/
public void setup(ModelRootImpl modelRoot, RenderersRoot vl) {
serverControls.setup(modelRoot, dialogueBoxController);
if (!modelRoot.hasBeenSetup)
throw new IllegalStateException();
ReadOnlyWorld world = modelRoot.getWorld();
if (world.size(SKEY.TRACK_RULES) > 0) {
trackMoveProducer = new TrackMoveProducer(modelRoot);
stationBuildModel = new StationBuildModel(new StationBuilder(
modelRoot), vl, modelRoot);
}
}

testConstructor

Class: jfreerails.world.top.WorldImplTest

Documentation

No documentation available

Source Code

public void testConstructor() {
World w = new WorldImpl();
assertEquals("The width should be zero", 0, w.getMapWidth());
assertEquals("The height should be zero", 0, w.getMapHeight());
}

convertToClass

Class: jfreerails.util.ClassPath

Documentation

/**
* @param classFile
* a class file listed on the classpath itself.
*/

Source Code

/**
* @param classFile
* a class file listed on the classpath itself.
*/
protected String convertToClass(File classFile) {
return getClassNameFrom(classFile.getName());
}

removeLastActiveEntity

Class: jfreerails.world.top.World

Documentation

No documentation available

Source Code

Activity removeLastActiveEntity(FreerailsPrincipal principal);

Called Methods

No outgoing method calls

previousJButtonActionPerformed

Class: jfreerails.client.view.TrainDialogueJPanel

Documentation

No documentation available

Source Code

private void previousJButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_previousJButtonActionPerformed
// Add your handling code here:
if (wi.previous()) {
display(wi.getIndex());
} else {
logger.warning("Couldn't get previous");
}
}// GEN-LAST:event_previousJButtonActionPerformed

TrainPathIntIterator

Class: jfreerails.controller.TrainPathIntIterator

Documentation

No documentation available

Source Code

public TrainPathIntIterator(FlatTrackExplorer t) {
trackExplorer = t;
}

Called Methods

No outgoing method calls

testCalculateAmountToAdd

Class: jfreerails.server.CargoAtStationsGeneratorTest

Documentation

No documentation available

Source Code

public void testCalculateAmountToAdd() {
CargoAtStationsGenerator cargoGenerator = new CargoAtStationsGenerator();
int amount = cargoGenerator.calculateAmountToAdd(12, 0);
assertEquals(1, amount);
assertCorrectTotalAddedOverYear(0);
assertCorrectTotalAddedOverYear(12);
assertCorrectTotalAddedOverYear(14);
assertCorrectTotalAddedOverYear(140);
assertCorrectTotalAddedOverYear(3);
}

List1DDiff

Class: jfreerails.util.List1DDiff

Documentation

No documentation available

Source Code

public List1DDiff(SortedMap<ListKey, Object> diffs, List1D<T> list,
Enum listID) {
super(diffs, listID);
underlyingList = list;
}

getListChanges

Class: jfreerails.move.WorldDiffMove

Documentation

No documentation available

Source Code

public CompositeMove getListChanges() {
return listChanges;
}

Called Methods

No outgoing method calls

start_TrackSet

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void start_TrackSet(final Attributes meta) throws SAXException {
ruleList = new ArrayList<TrackRule>();
}

Called Methods

No outgoing method calls

endDocument

Class: jfreerails.server.parser.CargoAndTerrainParser

Documentation

/**
* This SAX interface method is implemented by the parser.
*
*/

Source Code

/**
* This SAX interface method is implemented by the parser.
*
*/
public final void endDocument() throws SAXException {
}

Called Methods

No outgoing method calls

testAppend

Class: jfreerails.world.common.ImIntsTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.world.common.ImInts.append(int...)'
*/
public void testAppend() {
int[] a = { 1, 2, 3 };
int[] b = { 4, 5, 6, 7 };
int[] c = { 1, 2, 3, 4, 5, 6, 7 };
ImInts ai = new ImInts(a);
ImInts ci = new ImInts(c);
assertFalse(ci.equals(ai));
assertEquals(ci, ai.append(b));
}

paintCursor

Class: jfreerails.client.view.FreerailsCursor

Documentation

/**
* Paints the cursor. The method calculates position to paint it based on
* the tile size and the cursor's map position.
*
* @param g
* The graphics object to paint the cursor on.
* @param tileSize
* The dimensions of a tile.
*/

Source Code

/**
* Paints the cursor. The method calculates position to paint it based on
* the tile size and the cursor's map position.
*
* @param g
* The graphics object to paint the cursor on.
* @param tileSize
* The dimensions of a tile.
*/
public void paintCursor(Graphics g, Dimension tileSize) {
Graphics2D g2 = (Graphics2D) g;
TrackMoveProducer.BuildMode buildMode = (TrackMoveProducer.BuildMode) modelRoot
.getProperty(ModelRoot.Property.TRACK_BUILDER_MODE);
ImPoint cursorMapPosition = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.CURSOR_POSITION);
/* Has the cursor moved since we last painted it? */
if (!cursorMapPosition.equals(lastCursorPosition)) {
lastCursorPosition = cursorMapPosition;
timeArrived = System.currentTimeMillis();
}
int x = cursorMapPosition.x * tileSize.width;
int y = cursorMapPosition.y * tileSize.height;
Image cursor = null;
switch (buildMode) {
case BUILD_TRACK:
cursor = buildTrack;
break;
case REMOVE_TRACK:
cursor = removeTrack;
break;
case UPGRADE_TRACK:
cursor = upgradeTrack;
break;
case IGNORE_TRACK:
cursor = infoMode;
break;
case BUILD_STATION:
cursor = buildTrack;
break;
}
Boolean b = (Boolean) modelRoot
.getProperty(ModelRoot.Property.IGNORE_KEY_EVENTS);
long time = System.currentTimeMillis() - timeArrived;
boolean show = ((time / 500) % 2) == 0;
if (show && !b.booleanValue()) {
g.drawImage(cursor, x, y, null);
}
// Second, draw a message below the cursor if appropriate.
String message = (String) modelRoot
.getProperty(ModelRoot.Property.CURSOR_MESSAGE);
if (null != message && !message.equals("")) {
int fontSize = 12;
Font font = new Font("Arial", 0, fontSize);
FontRenderContext frc = g2.getFontRenderContext();
TextLayout layout = new TextLayout(message, font, frc);
// We want the message to be centered below the cursor.
float visibleAdvance = layout.getVisibleAdvance();
float textX = (x + (tileSize.width / 2) - (visibleAdvance / 2));
float textY = y + tileSize.height + fontSize + 5;
g.setColor(java.awt.Color.white);
layout.draw(g2, textX, textY);
}
// Draw a big white dot at the target point.
ImPoint targetPoint = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.THINKING_POINT);
if (null != targetPoint) {
time = System.currentTimeMillis();
int dotSize;
if ((time % 500) > 250) {
dotSize = BuildTrackRenderer.BIG_DOT_WIDTH;
} else {
dotSize = BuildTrackRenderer.SMALL_DOT_WIDTH;
}
g.setColor(Color.WHITE);
x = targetPoint.x * tileSize.width + (tileSize.width - dotSize) / 2;
y = targetPoint.y * tileSize.width + (tileSize.height - dotSize)
/ 2;
g.fillOval(x, y, dotSize, dotSize);
}
}

processPreMove

Class: experimental.SimpleMoveReceiver

Documentation

No documentation available

Source Code

public void processPreMove(PreMove pm) {
processMove(pm.generateMove(w));
}

tryUndoMove

Class: jfreerails.move.Move

Documentation

/**
* Tests whether this Move can be undone on the specified world object, this
* method should leave the world object unchanged.
*/

Source Code

/**
* Tests whether this Move can be undone on the specified world object, this
* method should leave the world object unchanged.
*/
MoveStatus tryUndoMove(World w, FreerailsPrincipal p);

Called Methods

No outgoing method calls

countStations

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

private void countStations() {
NonNullElements stations = new NonNullElements(KEY.STATIONS, modelRoot
.getWorld(), modelRoot.getPrincipal());
boolean enabled;
if (stations.size() > 0) {
enabled = true;
} else {
enabled = false;
}
this.trainsJTabPane.setStationTabEnabled(enabled);
this.stationInfoJMenuItem.setEnabled(enabled);
}

getReason

Class: jfreerails.controller.MessageStatus

Documentation

/** Returns the reason the command failed, may be null. */

Source Code

/** Returns the reason the command failed, may be null. */
public String getReason() {
return reason;
}

Called Methods

No outgoing method calls

undoLastTrackMove

Class: jfreerails.controller.TrackMoveProducer

Documentation

No documentation available

Source Code

public MoveStatus undoLastTrackMove() {
clearStackIfStale();
if (moveStack.size() > 0) {
Move m = moveStack.pop();
UndoMove undoMove = new UndoMove(m);
MoveStatus ms = executor.doMove(undoMove);
if (!ms.ok) {
return MoveStatus.moveFailed("Can not undo building track!");
}
return ms;
}
return MoveStatus.moveFailed("No track to undo building!");
}

testToString

Class: jfreerails.world.top.KEYTest

Documentation

No documentation available

Source Code

public void testToString() {
assertEquals("Key.toString() should return the field name", "TRAINS",
KEY.TRAINS.toString());
}

IntLine

Class: jfreerails.world.common.IntLine

Documentation

/**
* @param xx1
* x of the first point
* @param yy1
* y of the first point
* @param xx2
* x of the second point
* @param yy2
* y of the second point
*/

Source Code

/**
* @param xx1
* x of the first point
* @param yy1
* y of the first point
* @param xx2
* x of the second point
* @param yy2
* y of the second point
*/
public IntLine(int xx1, int yy1, int xx2, int yy2) {
x1 = xx1;
y1 = yy1;
x2 = xx2;
y2 = yy2;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.train.WagonType

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = typeCategory;
result = 29 * result + typeName.hashCode();
return result;
}

Called Methods

No outgoing method calls

setTrainDetailsButtonActionListener

Class: jfreerails.client.view.TrainDialogueJPanel

Documentation

No documentation available

Source Code

void setTrainDetailsButtonActionListener(ActionListener l) {
ActionListener[] oldListeners = trainListJButton.getActionListeners();
for (int i = 0; i < oldListeners.length; i++) {
trainListJButton.removeActionListener(oldListeners[i]);
}
this.trainListJButton.addActionListener(l);
}

Called Methods

No outgoing method calls

formMouseMoved

Class: jfreerails.client.view.SelectStationJPanel

Documentation

No documentation available

Source Code

private void formMouseMoved(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_formMouseMoved
// Add your handling code here:
double x = evt.getX();
x = x / scale + visibleMapTiles.x;
double y = evt.getY();
y = y / scale + visibleMapTiles.y;
NearestStationFinder stationFinder = new NearestStationFinder(
this.world, this.principal);
int station = stationFinder.findNearestStation((int) x, (int) y);
if (selectedStationID != station
&& station != NearestStationFinder.NOT_FOUND) {
selectedStationID = station;
cargoWaitingAndDemandedJPanel1.display(selectedStationID);
this.validate();
this.repaint();
}
}// GEN-LAST:event_formMouseMoved

hasSetupBeenCalled

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

protected boolean hasSetupBeenCalled() {
return hasSetupBeenCalled;
}

Called Methods

No outgoing method calls

getStationName

Class: jfreerails.world.station.StationModel

Documentation

No documentation available

Source Code

public String getStationName() {
return name;
}

Called Methods

No outgoing method calls

setUp

Class: jfreerails.move.ChangeProductionAtEngineShopMoveTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
super.setUp();
getWorld().add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
new StationModel());
getWorld().add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
new StationModel());
getWorld().add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
new StationModel());
WagonAndEngineTypesFactory wetf = new WagonAndEngineTypesFactory();
wetf.addTypesToWorld(getWorld());
engineType = 0;
wagonType = 0;
wagons = new int[] { wagonType, wagonType };
after = new ImList<PlannedTrain>(new PlannedTrain(
engineType, wagons));
}

doMove

Class: jfreerails.move.AddItemToSharedListMove

Documentation

No documentation available

Source Code

public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.isOk()) {
w.add(listKey, this.item);
}
return ms;
}

testGetNewTemplateNumber

Class: jfreerails.world.common.StepTest

Documentation

No documentation available

Source Code

public void testGetNewTemplateNumber() {
assertEquals(Step.NORTH.get8bitTemplate(), 1);
assertEquals(Step.NORTH_EAST.get8bitTemplate(), 2);
assertEquals(Step.EAST.get8bitTemplate(), 4);
}

aHeadEqualsBTail

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public static boolean aHeadEqualsBTail(TrainPositionOnMap a,
TrainPositionOnMap b) {
int aHeadX = a.getX(0);
int aHeadY = a.getY(0);
int bTailX = b.getX(b.getLength() - 1);
int bTailY = b.getY(b.getLength() - 1);
if (aHeadX == bTailX && aHeadY == bTailY) {
return true;
}
return false;
}

get9bitTemplate

Class: jfreerails.world.common.Step

Documentation

No documentation available

Source Code

public int get9bitTemplate() {
return flatTrackTemplate;
}

Called Methods

No outgoing method calls

itemRemoved

Class: jfreerails.network.specifics.SimpleServerGameModel

Documentation

No documentation available

Source Code

public void itemRemoved(KEY key, int index, FreerailsPrincipal principal) {
}

Called Methods

No outgoing method calls

set

Class: jfreerails.util.List2DImpl

Documentation

No documentation available

Source Code

public void set(int d1, int d2, T element) {
elementData.get(d1).set(d2, element);
}

Called Methods

No outgoing method calls

main

Class: experimental.DialogueBoxTester

Documentation

No documentation available

Source Code

public static void main(String args[]) {
DialogueBoxTester test = new DialogueBoxTester();
test.setVisible(true);
}

Called Methods

No outgoing method calls

getNextScheduledOrder

Class: jfreerails.world.train.Schedule

Documentation

No documentation available

Source Code

int getNextScheduledOrder();

Called Methods

No outgoing method calls

getNaturalNumber

Class: jfreerails.world.top.NonNullElements

Documentation

No documentation available

Source Code

public int getNaturalNumber() {
return getRowID() + 1;
}

getTicks

Class: jfreerails.world.common.GameTime

Documentation

No documentation available

Source Code

public int getTicks() {
return ticks;
}

Called Methods

No outgoing method calls

showReportBug

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showReportBug(){
CopyableTextJPanel ct = new CopyableTextJPanel();
ct.setText(ReportBugTextGenerator.genText());
showContent(ct);
}

componentResized

Class: jfreerails.controller.JFrameMinimumSizeEnforcer

Documentation

No documentation available

Source Code

public void componentResized(ComponentEvent arg0) {
Component c = arg0.getComponent();
int width = c.getWidth();
int height = c.getHeight();
// we check if either the width
// or the height are below minimum
boolean resize = false;
if (width < minWidth) {
resize = true;
width = minWidth;
}
if (height < minHeight) {
resize = true;
height = minHeight;
}
if (resize) {
c.setSize(width, height);
}
}

Called Methods

No outgoing method calls

assertBuildTrackSucceeds

Class: jfreerails.move.ChangeTrackPieceCompositeMoveTest

Documentation

No documentation available

Source Code

private void assertBuildTrackSucceeds(ImPoint p, Step v, TrackRule rule) {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(p, v, rule, rule, getWorld(),
MapFixtureFactory.TEST_PRINCIPAL);
Move moveAndTransaction = transactionsGenerator.addTransactions(move);
MoveStatus status = moveAndTransaction.doMove(getWorld(),
Player.AUTHORITATIVE);
assertEquals(true, status.isOk());
}

calculateQuantity

Class: jfreerails.world.top.ItemsTransactionAggregator

Documentation

No documentation available

Source Code

public int calculateQuantity() {
QuantitiesAndValues qnv = calculateQuantitiesAndValues();
return qnv.quantities[0];
}

createHelpMenu

Class: experimental.SimpleComponentFactoryImpl2

Documentation

No documentation available

Source Code

public JMenu createHelpMenu() {
return null;
}

Called Methods

No outgoing method calls

generateFileNameNumber

Class: jfreerails.client.renderer.SpecialTileRenderer

Documentation

No documentation available

Source Code

@Override
protected String generateFileNameNumber(int i) {
throw new UnsupportedOperationException();
}

Called Methods

No outgoing method calls

checkT

Class: jfreerails.world.train.CompositeSpeedAgainstTime

Documentation

No documentation available

Source Code

void checkT(double t) {
if (t < 0d || t > finalT)
throw new IllegalArgumentException("t="+t+", but duration="+finalT);
}

Called Methods

No outgoing method calls

makeTransparent

Class: experimental.GenerateTrainHighlights

Documentation

No documentation available

Source Code

static Color makeTransparent(Color before, int alpha){
return new Color(before.getRed(), before.getGreen(), before.getBlue(), alpha);
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.world.accounts.AddItemTransaction

Documentation

No documentation available

Source Code

@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("AddItemTransaction ");
sb.append(category);
sb.append(", type ");
sb.append(type);
sb.append(", quantity ");
sb.append(quantity);
sb.append(", amount ");
sb.append(amount);
return sb.toString();
}

Called Methods

No outgoing method calls

buildStation

Class: jfreerails.server.MapCustomizer

Documentation

No documentation available

Source Code

public MapCustomizer buildStation(ImPoint a) {
MoveStatus ms = stationBuilder.buildStation(a);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
return this;
}

setup

Class: jfreerails.client.view.BrokerJFrame

Documentation

No documentation available

Source Code

public void setup(ModelRoot m, RenderersRoot vl,
Action closeAction) {
this.done.setAction(closeAction);
}

Called Methods

No outgoing method calls

setUp

Class: jfreerails.network.specifics.MovePrecommitterTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
w = new WorldImpl(10, 10);
committer = new MovePrecommitter(w);
}

Called Methods

No outgoing method calls

sizeD3

Class: jfreerails.util.List3DImpl

Documentation

No documentation available

Source Code

public int sizeD3(int d1, int d2) {
return elementData.get(d1).get(d2).size();
}

Called Methods

No outgoing method calls

saveGame

Class: jfreerails.network.specifics.SavedGamesManager4UnitTests

Documentation

No documentation available

Source Code

public void saveGame(Serializable w, String name) throws IOException {
// Make a copy so that the saved version's state cannot be changed.
Serializable copy = Utils.cloneBySerialisation(w);
this.savedGames.put(name, copy);
}

getID

Class: jfreerails.network.specifics.RefreshListOfGamesMessage2Server

Documentation

No documentation available

Source Code

public int getID() {
return id;
}

Called Methods

No outgoing method calls

hasPrevious

Class: jfreerails.world.top.ActivityIteratorImpl

Documentation

No documentation available

Source Code

public boolean hasPrevious() {
return activityIndex >= 1;
}

Called Methods

No outgoing method calls

paintTrain

Class: jfreerails.client.renderer.TrainRenderer

Documentation

No documentation available

Source Code

public void paintTrain(Graphics g, TrainModel train, List<Entry<Point, Step>> positions) {
for (int i = 0; i < positions.size(); i++) {
TrainImages trainImages;
if (i == 0) {
trainImages = rr.getEngineImages(train.getEngineType());
} else {
int type = train.getWagon(i - 1);
trainImages = rr.getWagonImages(type);
}
Entry<Point, Step> entry = positions.get(i);
Image image = trainImages.getOverheadImage(entry.getValue().getID());
Point p = entry.getKey();
g.drawImage(image, p.x - 15, p.y - 15, null);
}
}

GameRules

Class: jfreerails.world.top.GameRules

Documentation

No documentation available

Source Code

private GameRules(boolean mustConnect, boolean canConnect2others) {
canConnect2OtherRRTrack = canConnect2others;
mustConnect2ExistingTrack = mustConnect;
}

Called Methods

No outgoing method calls

getMaximumConsecutivePieces

Class: jfreerails.world.track.TrackRule

Documentation

No documentation available

Source Code

int getMaximumConsecutivePieces();

Called Methods

No outgoing method calls

displayTrain

Class: jfreerails.client.view.TrainDescriptionJPanel

Documentation

No documentation available

Source Code

public void displayTrain(int newTrainNumber) {
NonNullElements it = new NonNullElements(KEY.TRAINS, w, principal);
it.gotoIndex(newTrainNumber);
this.trainNumber = newTrainNumber;
trainViewJPanel1.display(newTrainNumber);
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
newTrainNumber);
for (int i = 0; i < train.getNumberOfWagons(); i++) {
// this.sideOnTrainViewJPanel1.addWagon(train.getWagon(i));
}
int cargoBundleID = train.getCargoBundleID();
ImmutableCargoBundle cb = (ImmutableCargoBundle) w.get(
principal, KEY.CARGO_BUNDLES, cargoBundleID);
String s = "Train #" + it.getNaturalNumber() + ": ";
int numberOfTypesInBundle = 0;
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
int amount = cb.getAmount(i);
if (0 != amount) {
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, i);
String cargoTypeName = ct.getDisplayName();
if (0 != numberOfTypesInBundle) {
s += "; ";
}
numberOfTypesInBundle++;
s += cargoTypeName + " (" + amount + ")";
}
}
if (0 == numberOfTypesInBundle) {
s += "no cargo";
}
s += ".";
this.jLabel1.setText(s);
this.lastCargoBundle = cb;
this.lastTrain = train;
}

isInRightDirection

Class: jfreerails.client.view.NearestStationFinder

Documentation

/**
* Returns true if the angle between direction and the vector (deltaX,
* deltaY) is less than 45 degrees.
*/

Source Code

/**
* Returns true if the angle between direction and the vector (deltaX,
* deltaY) is less than 45 degrees.
*/
private boolean isInRightDirection(Step direction, int deltaX, int deltaY) {
boolean isDiagonal = direction.deltaX * direction.deltaY != 0;
boolean sameXDirection = (direction.deltaX * deltaX) > 0;
boolean sameYDirection = (direction.deltaY * deltaY > 0);
boolean deltaXisLongerThanDeltaY = deltaX * deltaX < deltaY * deltaY;
if (isDiagonal) {
return sameXDirection && sameYDirection;
}
if (0 == direction.deltaX) {
return deltaXisLongerThanDeltaY && sameYDirection;
}
return !deltaXisLongerThanDeltaY && sameXDirection;
}

Called Methods

No outgoing method calls

contains

Class: jfreerails.world.common.ImSet

Documentation

No documentation available

Source Code

public boolean contains(E element) {
return hashSet.contains(element);
}

Called Methods

No outgoing method calls

calcT

Class: jfreerails.world.train.SpeedAgainstTime

Documentation

/**
* Returns the time taken to travel distance s. The returned value, t,
* satisfies the following conditions:
* <ol>
* <li>t >= 0</li>
* <li>t <= getT()</li>
* <li>t = 0 if s = 0 </li>
* <li>t = getT() if s = getS()</li>
* </ol>
*
* @throws IllegalArgumentException
* iff s < 0 or s > getS()
* @return t
*/

Source Code

/**
* Returns the time taken to travel distance s. The returned value, t,
* satisfies the following conditions:
* <ol>
* <li>t >= 0</li>
* <li>t <= getT()</li>
* <li>t = 0 if s = 0 </li>
* <li>t = getT() if s = getS()</li>
* </ol>
*
* @throws IllegalArgumentException
* iff s < 0 or s > getS()
* @return t
*/
double calcT(double s);

Called Methods

No outgoing method calls

occupiedTrackSection

Class: jfreerails.controller.TrainAccessor

Documentation

No documentation available

Source Code

public HashSet<TrackSection> occupiedTrackSection(double time){
TrainMotion tm = findCurrentMotion(time);
PathOnTiles path = tm.getPath();
HashSet<TrackSection> sections = new HashSet<TrackSection>();
ImPoint start = path.getStart();
int x = start.x;
int y = start.y;
for (int i = 0; i < path.steps(); i++) {
Step s = path.getStep(i);
ImPoint tile = new ImPoint(x, y);
x+=s.deltaX;
y+=s.deltaY;
sections.add(new TrackSection(s, tile));
}
return sections;
}

removeAllStopsAtStation

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public void removeAllStopsAtStation(int stationNumber) {
int i = 0;
while (i < this.getNumOrders()) {
TrainOrdersModel order = this.getOrder(i);
if (order.getStationID() == stationNumber) {
this.removeOrder(i);
} else {
i++;
}
}
}

canBuildTrack

Class: jfreerails.controller.BuildTrackExplorer

Documentation

/**
* <p>
* Tests whether we can build track in the direction specified by
* m_direction.
* </p>
*
* <p>
* If we enter a tile from a given direction, the tiles we can build track
* to depend on the following. (1) The terrain type of the surrounding tiles -
* track can only be built on certain terrain types. (2) The direction we
* entered the current tile from. (3) Any existing track on the current tile -
* limits possible track configurations. (4) The terrain type of the current
* tile - terrain type determines which track types and hence which track
* configurations can be built.
* </p>
*
*/

Source Code

/**
* <p>
* Tests whether we can build track in the direction specified by
* m_direction.
* </p>
*
* <p>
* If we enter a tile from a given direction, the tiles we can build track
* to depend on the following. (1) The terrain type of the surrounding tiles -
* track can only be built on certain terrain types. (2) The direction we
* entered the current tile from. (3) Any existing track on the current tile -
* limits possible track configurations. (4) The terrain type of the current
* tile - terrain type determines which track types and hence which track
* configurations can be built.
* </p>
*
*/
private boolean canBuildTrack() {
// Check that we are not doubling back on ourselves.
Step opposite2current = currentPosition.cameFrom().getOpposite();
int currentX = currentPosition.getX();
int currentY = currentPosition.getY();
int directionWeCameFrom = opposite2current.getID();
int directionWeCameFromPlus = (directionWeCameFrom + 1) % 8;
int directionWeCameFromMinus = (directionWeCameFrom + 7) % 8;
if (directionInt == directionWeCameFrom
|| directionInt == directionWeCameFromPlus
|| directionInt == directionWeCameFromMinus) {
return false;
}
// Check that we are not going off the map.
Step directionOfNextTile = Step.getInstance(directionInt);
int newX = currentX + directionOfNextTile.getDx();
int newY = currentY + directionOfNextTile.getDy();
if (!world.boundsContain(newX, newY)) {
return false;
}
TrackRule rule4nextTile;
TrackRule rule4lastTile;
// Determine the track rule for the next tile.
final FreerailsTile nextTile = (FreerailsTile) world.getTile(newX,
newY);
// Check there is not another players track at nextTile.
if (nextTile.hasTrack()) {
if (nextTile.getTrackPiece().getOwnerID() != world.getID(principal)) {
return false;
}
}
rule4nextTile = getAppropriateTrackRule(newX, newY);
if (null == rule4nextTile) {
return false; // We can't build track on the tile.
}
rule4lastTile = getAppropriateTrackRule(currentX, currentY);
if (null == rule4lastTile) {
return false; // We can't build track on the tile.
}
// Determine the track rule for the current tile.
FreerailsTile currentTile = (FreerailsTile) world.getTile(currentX,
currentY);
// Check for illegal track configurations.
final TrackConfiguration trackAlreadyPresent1 = currentTile
.getTrackPiece().getTrackConfiguration();
final TrackConfiguration trackAlreadyPresent2 = nextTile
.getTrackPiece().getTrackConfiguration();
TrackConfiguration fromConfig = trackAlreadyPresent1;
fromConfig = TrackConfiguration.add(fromConfig, opposite2current);
fromConfig = TrackConfiguration.add(fromConfig, TILE_CENTER);
Step goingTo = Step.getInstance(directionInt);
fromConfig = TrackConfiguration.add(fromConfig, goingTo);
if (!rule4lastTile.trackPieceIsLegal(fromConfig)) {
return false;
}
// Check for diagonal conflicts.
if (directionOfNextTile.isDiagonal()) {
int x2check = currentX;
int y2check = currentY + directionOfNextTile.deltaY;
// We did a bounds check above.
assert (world.boundsContain(x2check, y2check));
FreerailsTile tile2Check = (FreerailsTile) world.getTile(x2check,
y2check);
TrackConfiguration config2check = tile2Check
.getTrackPiece().getTrackConfiguration();
Step vector2check = Step.getInstance(directionOfNextTile.deltaX,
-directionOfNextTile.deltaY);
if (config2check.contains(vector2check)) {
// then we have a diagonal conflict.
return false;
}
}
// Check for illegal track configurations on the tile we are entering.
TrackConfiguration fromConfig2 = trackAlreadyPresent2;
fromConfig2 = TrackConfiguration.add(fromConfig2, TILE_CENTER);
Step goingBack = Step.getInstance(directionInt).getOpposite();
fromConfig2 = TrackConfiguration.add(fromConfig2, goingBack);
if (!rule4nextTile.trackPieceIsLegal(fromConfig2)) {
return false;
}
/*
* Set the using existing track. We do this because a path that uses
* existing track is cheaper to build.
*/
usingExistingTrack = trackAlreadyPresent1.contains(goingTo);
return true;
}

init

Class: jfreerails.network.specifics.ServerGameModel

Documentation

No documentation available

Source Code

void init(MoveReceiver moveExecutor);

Called Methods

No outgoing method calls

setIgnoreKeyEvents

Class: jfreerails.client.top.UserInputOnMapController

Documentation

No documentation available

Source Code

private void setIgnoreKeyEvents(boolean ignoreKeyEvents) {
modelRoot.setProperty(Property.IGNORE_KEY_EVENTS, Boolean
.valueOf(ignoreKeyEvents));
}

readFromServer

Class: jfreerails.network.Connection2Server

Documentation

/**
* Returns an array containing all the objects read from the server since
* the last time this method or waitForObjectFromServer() was called, if no
* objects have been received, it returns an empty array rather than
* blocking.
*/

Source Code

/**
* Returns an array containing all the objects read from the server since
* the last time this method or waitForObjectFromServer() was called, if no
* objects have been received, it returns an empty array rather than
* blocking.
*/
FreerailsSerializable[] readFromServer() throws IOException;

Called Methods

No outgoing method calls

setHtml

Class: jfreerails.client.view.BrokerJFrame

Documentation

No documentation available

Source Code

void setHtml(String s) {
htmlJLabel.setText(s);
}

Called Methods

No outgoing method calls

start_ListOfTrackPieceTemplates

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void start_ListOfTrackPieceTemplates(final Attributes meta)
throws SAXException {
legalTemplates = new ArrayList<String>();
}

Called Methods

No outgoing method calls

doMove

Class: jfreerails.move.TimeTickMove

Documentation

No documentation available

Source Code

public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryDoMove(w, p);
if (status.ok) {
w.setTime(newTime);
}
return status;
}

getCategory

Class: jfreerails.world.top.ItemsTransactionAggregator

Documentation

No documentation available

Source Code

public Transaction.Category getCategory() {
return category;
}

Called Methods

No outgoing method calls

doMove

Class: jfreerails.move.AddItemToListMove

Documentation

No documentation available

Source Code

public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.isOk()) {
w.add(this.principal, listKey, this.item);
}
return ms;
}

testGetIntIntInt

Class: jfreerails.util.List3DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List3DDiff.get(int, int, int)'
*/
public void testGetIntIntInt() {
underlying.addD1();
underlying.addD1();
underlying.addD2(1);
underlying.addD2(1);
underlying.addD3(1, 1, new Integer(1));
assertEquals(new Integer(1), diffs.get(1,1,0));
diffs.addD3(1, 1, new Integer(2));
diffs.addD3(1, 1, new Integer(3));
assertEquals(new Integer(2), diffs.get(1,1,1));
assertEquals(new Integer(3), diffs.get(1,1,2));
}

previousActivity

Class: jfreerails.world.top.ActivityIteratorImpl

Documentation

No documentation available

Source Code

public void previousActivity() throws NoSuchElementException {
if (!hasPrevious()) {
throw new NoSuchElementException();
}
activityIndex--;
ant = currentList.get(activityIndex);
}

Called Methods

  • jfreerails.world.top.WorldImpl.ActivityIteratorImpl.hasPrevious (external)

List1DImpl

Class: jfreerails.util.List1DImpl

Documentation

No documentation available

Source Code

public List1DImpl(int initialSize) {
elementData = new ArrayList<T>();
for (int i = 0; i < initialSize; i++) {
elementData.add(null);
}
}

Called Methods

No outgoing method calls

getProperty

Class: jfreerails.controller.ModelRoot

Documentation

No documentation available

Source Code

Object getProperty(Property property);

Called Methods

No outgoing method calls

update

Class: jfreerails.server.InterestChargeMoveGenerator

Documentation

No documentation available

Source Code

public void update(World w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
Move m = generateMove(w, principal);
moveReceiver.processMove(m);
}
}

getEngineImages

Class: jfreerails.client.renderer.RenderersRoot

Documentation

No documentation available

Source Code

TrainImages getEngineImages(int type);

Called Methods

No outgoing method calls

convertToPackageName

Class: experimental.GenerateDependenciesXmlAndHtml

Documentation

No documentation available

Source Code

private String convertToPackageName(String packagesString) {
if (!isPackageNameOk(packagesString)) {
throw new IllegalArgumentException(packagesString);
}
packagesString = packagesString.replace('/', '.');
/*
* Remove the last two characters, so that jfreerails.world.**.* - >
* jfreerails.world.** and jfreerails.util.* -> jfreerails.util
*/
packagesString = packagesString.substring(0,
packagesString.length() - 2);
return packagesString;
}

getWorldDiffs

Class: jfreerails.client.renderer.BuildTrackRenderer

Documentation

No documentation available

Source Code

private WorldDiffs getWorldDiffs() {
if (modelRoot == null) {
return null;
}
return (WorldDiffs) modelRoot
.getProperty(ModelRoot.Property.PROPOSED_TRACK);
}

ScreenHandler

Class: jfreerails.controller.ScreenHandler

Documentation

No documentation available

Source Code

public ScreenHandler(JFrame f, int mode) {
frame = f;
this.mode = mode;
}

Called Methods

No outgoing method calls

getRate

Class: jfreerails.world.terrain.Production

Documentation

No documentation available

Source Code

public int getRate() {
return rate;
}

Called Methods

No outgoing method calls

formComponentShown

Class: jfreerails.client.view.LoadGameJPanel

Documentation

No documentation available

Source Code

private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
}//GEN-LAST:event_formComponentShown

Called Methods

No outgoing method calls

setServerCommandReceiver

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public void setServerCommandReceiver(
ServerCommandReceiver serverCommandReceiver) {
this.serverCommandReceiver = serverCommandReceiver;
}

Called Methods

No outgoing method calls

getPrincipal

Class: jfreerails.move.ChangeItemInListMove

Documentation

No documentation available

Source Code

public FreerailsPrincipal getPrincipal() {
return principal;
}

Called Methods

No outgoing method calls

ProgressJPanel

Class: jfreerails.launcher.ProgressJPanel

Documentation

/** Creates new form ProgressJPanel */

Source Code

/** Creates new form ProgressJPanel */
public ProgressJPanel(LauncherInterface owner) {
this.owner = owner;
initComponents();
progressBar.setMaximum(numSteps * 100);
}

getScrollableTracksViewportWidth

Class: jfreerails.client.view.MapViewJComponent

Documentation

No documentation available

Source Code

public boolean getScrollableTracksViewportWidth() {
return false;
}

Called Methods

No outgoing method calls

throwsException

Class: jfreerails.world.train.PathOnTilesTest

Documentation

No documentation available

Source Code

boolean throwsException(ImPoint start, Step[] vectors) {
try {
new PathOnTiles(start, vectors);
return false;
} catch (Exception e) {
return true;
}
}

Called Methods

No outgoing method calls

tryUndoMove

Class: jfreerails.move.WorldDiffMove

Documentation

No documentation available

Source Code

public MoveStatus tryUndoMove(World world, FreerailsPrincipal p) {
MoveStatus ms = tryMapChanges(world, true);
if (!ms.ok)
return ms;
return ms = listChanges.tryUndoMove(world, p);
}

getStartOfYear

Class: jfreerails.world.common.GameCalendar

Documentation

No documentation available

Source Code

public GameTime getStartOfYear(GameTime t) {
int year = getYear(t.getTicks());
int ticks = getTicks(year);
return new GameTime(ticks);
}

removeLastD1

Class: jfreerails.util.List2DDiff

Documentation

No documentation available

Source Code

public int removeLastD1() {
return super.removeLastList();
}

createTrainsJTabPane

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

public JTabbedPane createTrainsJTabPane() {
return trainsJTabPane;
}

Called Methods

No outgoing method calls

display

Class: jfreerails.client.view.SelectStationJPanel

Documentation

No documentation available

Source Code

public void display(MutableSchedule newSchedule, int orderNumber) {
this.schedule = newSchedule;
this.selectedOrderNumber = orderNumber;
TrainOrdersModel order = newSchedule.getOrder(selectedOrderNumber);
this.selectedStationID = order.getStationID();
// Set the text on the title JLabel.
this.jLabel1.setText("Stop " + String.valueOf(selectedOrderNumber + 1));
// Set the station info panel to show the current selected station.
cargoWaitingAndDemandedJPanel1.display(selectedStationID);
}

doMove

Class: jfreerails.move.NextActivityMove

Documentation

No documentation available

Source Code

public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.ok)
w.add(principal, index, activity);
return ms;
}

storeRunningTotal

Class: jfreerails.controller.FinancialDataGatherer

Documentation

No documentation available

Source Code

@Override
protected void storeRunningTotal(int timeIndex) {
// TODO Auto-generated method stub
super.storeRunningTotal(timeIndex);
}

testBankAccount

Class: jfreerails.world.top.WorldImplTest

Documentation

No documentation available

Source Code

public void testBankAccount(){
WorldImpl world = new WorldImpl();
Player p = new Player("Test", 0);
int playerID = world.addPlayer(p);
assertEquals(0, playerID);
FreerailsPrincipal fp = world.getPlayer(playerID).getPrincipal();
Transaction t = new AddItemTransaction(Category.BOND, 1, 2, new Money(100));
assertEquals(new Money(0), world.getCurrentBalance(fp));
world.addTransaction(fp, t);
assertEquals(1, world.getNumberOfTransactions(fp));
assertEquals(new Money(100), world.getCurrentBalance(fp));
Transaction t2 = world.getTransaction(fp, 0);
assertEquals(t, t2);
Transaction t3 = world.removeLastTransaction(fp);
assertEquals(t, t3);
assertEquals(new Money(0), world.getCurrentBalance(fp));
}

flush

Class: jfreerails.network.Connection2Client

Documentation

/** Flush the underlying stream. */

Source Code

/** Flush the underlying stream. */
void flush() throws IOException;

Called Methods

No outgoing method calls

getInstance

Class: jfreerails.move.RemoveStationMove

Documentation

No documentation available

Source Code

static RemoveStationMove getInstance(ReadOnlyWorld w,
ChangeTrackPieceMove removeTrackMove, FreerailsPrincipal principal) {
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
int stationIndex = -1;
while (wi.next()) {
StationModel station = (StationModel) wi.getElement();
if (station.x == removeTrackMove.getLocation().x
&& station.y == removeTrackMove.getLocation().y) {
// We have found the station!
stationIndex = wi.getIndex();
break;
}
}
if (-1 == stationIndex) {
throw new IllegalArgumentException("Could find a station at "
+ removeTrackMove.getLocation().x + ", "
+ removeTrackMove.getLocation().y);
}
StationModel station2remove = (StationModel) w.get(principal,
KEY.STATIONS, stationIndex);
ArrayList<Move> moves = new ArrayList<Move>();
moves.add(removeTrackMove);
moves.add(new RemoveItemFromListMove(KEY.STATIONS, stationIndex,
station2remove, principal));
// Now update any train schedules that include this station.
WorldIterator schedules = new NonNullElements(KEY.TRAIN_SCHEDULES, w,
principal);
while (schedules.next()) {
ImmutableSchedule schedule = (ImmutableSchedule) schedules
.getElement();
if (schedule.stopsAtStation(stationIndex)) {
MutableSchedule mutableSchedule = new MutableSchedule(schedule);
mutableSchedule.removeAllStopsAtStation(stationIndex);
Move changeScheduleMove = new ChangeTrainScheduleMove(schedules
.getIndex(), schedule, mutableSchedule
.toImmutableSchedule(), principal);
moves.add(changeScheduleMove);
}
}
return new RemoveStationMove(moves);
}

setOrder

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public void setOrder(int orderNumber, TrainOrdersModel order) {
if (orderNumber >= orders.size()) {
orders.add(order);
} else {
orders.set(orderNumber, order);
}
}

Called Methods

No outgoing method calls

start_ListOfLegalRoutesAcrossNode

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void start_ListOfLegalRoutesAcrossNode(final Attributes meta)
throws SAXException {
}

Called Methods

No outgoing method calls

resetProperties

Class: jfreerails.network.specifics.FreerailsClient

Documentation

No documentation available

Source Code

public final void resetProperties(HashMap newProperties) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException();
}

Called Methods

No outgoing method calls

accepted

Class: jfreerails.network.specifics.LogOnResponse

Documentation

No documentation available

Source Code

public static LogOnResponse accepted(int playerNumber) {
return new LogOnResponse(true, playerNumber, null);
}

Called Methods

No outgoing method calls

testBoundsOnSet2

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

public void testBoundsOnSet2() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
underlying.addD2(0, String.valueOf(3));
diffs.removeLastD2(0);
diffs.removeLastD2(0);
try {
assertEquals(1, diffs.size(0));
diffs.set(0, 2, String.valueOf(3));
fail();
} catch (Exception e) {
}
}

hashCode

Class: jfreerails.util.ListKey

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = type.hashCode();
result = 29 * result + listID.hashCode();
return result;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.train.TrainMotion

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = path.hashCode();
result = 29 * result + speeds.hashCode();
result = 29 * result + trainLength;
return result;
}

getInstance

Class: jfreerails.client.top.SynchronizedEventQueue

Documentation

No documentation available

Source Code

public static SynchronizedEventQueue getInstance() {
return instance;
}

Called Methods

No outgoing method calls

createCashJLabel

Class: jfreerails.client.top.GUIComponentFactoryTestImpl

Documentation

No documentation available

Source Code

public JLabel createCashJLabel() {
return cashjLabel;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.track.FreerailsTile

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final FreerailsTile that = (FreerailsTile) o;
if (terrainType != that.terrainType)
return false;
if (trackPiece != null ? !trackPiece.equals(that.trackPiece)
: that.trackPiece != null)
return false;
return true;
}

Called Methods

No outgoing method calls

setPositionFollowsMouse

Class: jfreerails.client.view.StationBuildModel

Documentation

No documentation available

Source Code

public void setPositionFollowsMouse(boolean positionFollowsMouse) {
this.positionFollowsMouse = positionFollowsMouse;
}

Called Methods

No outgoing method calls

testAddToHead

Class: jfreerails.world.train.TrainPositionOnMapTest

Documentation

No documentation available

Source Code

/*
* public void testAdd() { TrainPosition a, b, c, d, e, f, g, h , i, j;
* a=TrainPosition.createInstance(new int[] {10,20}, new int[]{11,22});
* b=TrainPosition.createInstance(new int[] {20, 30}, new int[]{22,33});
* c=TrainPosition.createInstance(new int[] {10, 30}, new int[]{11, 33});
*
* d=TrainPosition.add(a, b); assertEquals(d, c); e=TrainPosition.add(b, a);
* assertEquals(e, c);
*
*
* f = TrainPosition.createInstance( new int[] { 40, 50 }, new int[] { 44,
* 55 }); g = TrainPosition.createInstance( new int[] { 10, 30, 40 }, new
* int[] { 11, 33, 44 });
*
* i = TrainPosition.createInstance( new int[] { 10, 30, 50 }, new int[] {
* 11, 33, 55 }); j = TrainPosition.add(f, g); assertEquals(i, j);
*
*
* }
*/
/*
* public void testRemove() { TrainPosition a, b, c, d, e, f, g, h , i, j ,
* k; a=TrainPosition.createInstance(new int[] {10,20 ,40 , 50, 60}, new
* int[]{11,22, 44, 55 , 66}); b=TrainPosition.createInstance(new int[] {10,
* 20, 30}, new int[]{11,22,33}); c=TrainPosition.createInstance(new int[]
* {48, 50, 60}, new int[]{49,55, 66});
*
* d=TrainPosition.createInstance(new int[] {30, 40 , 50, 60}, new int[]{33,
* 44, 55, 66}); e=TrainPosition.createInstance(new int[] {10, 20, 40, 48},
* new int[]{11, 22, 44, 49});
*
* f=TrainPosition.remove(a, b); assertEquals(f, d);
*
* g=TrainPosition.remove(a, c); assertEquals(g, e);
*
* h = TrainPosition.createInstance( new int[] { 10, 30, 50 }, new int[] {
* 11, 33, 55 });
*
* i = TrainPosition.createInstance( new int[] { 10, 20 }, new int[] { 11,
* 22 });
*
* j = TrainPosition.createInstance( new int[] { 20, 30, 50 }, new int[] {
* 22, 33, 55 });
*
* k = TrainPosition.remove(h, i);
*
* assertEquals(k, j); }
*
*/
/*
* public void testCanBeAdded() { TrainPosition a, b, c, d;
* a=TrainPosition.createInstance(new int[] {10,20}, new int[]{11,22});
* b=TrainPosition.createInstance(new int[] {20, 30}, new int[]{22,33});
* c=TrainPosition.createInstance(new int[] {30, 40}, new int[]{33,44});
*
* assertTrue(TrainPosition.canBeAdded(a, b));
* assertTrue(TrainPosition.canBeAdded(b, a));
* assertTrue(TrainPosition.canBeAdded(b, c));
* assertTrue(!TrainPosition.canBeAdded(c, b));
*
* assertTrue(!TrainPosition.canBeAdded(a, c));
* assertTrue(!TrainPosition.canBeAdded(c, a));
*
* //Test that we cannot add a position to itself
* assertTrue(!TrainPosition.canBeAdded(a, a));
* assertTrue(!TrainPosition.canBeAdded(b, b));
* assertTrue(!TrainPosition.canBeAdded(c, c)); }
*/
/*
* public void testCanBeRemoved() { TrainPosition a, b, c, d;
* a=TrainPosition.createInstance(new int[] {10,20 ,40 , 50}, new
* int[]{11,22, 44, 55}); b=TrainPosition.createInstance(new int[] {10, 20,
* 30}, new int[]{11,22,33}); c=TrainPosition.createInstance(new int[] {30,
* 40, 50}, new int[]{33,44,55});
*
* assertTrue(TrainPosition.canBeRemoved(a, b));
*
* assertTrue(!TrainPosition.canBeRemoved(b, a));
*
* assertTrue(TrainPosition.canBeRemoved(a, c));
*
* assertTrue(!TrainPosition.canBeRemoved(c, a));
*
* //Test that we cannot remove a position from itself
* assertTrue(!TrainPosition.canBeRemoved(a, a));
* assertTrue(!TrainPosition.canBeRemoved(b, b));
* assertTrue(!TrainPosition.canBeRemoved(c, c)); }
*/
public void testAddToHead() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
TrainPositionOnMap d;
TrainPositionOnMap f;
TrainPositionOnMap g;
TrainPositionOnMap i;
TrainPositionOnMap j;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
b = TrainPositionOnMap.createInstance(new int[] { 20, 30 }, new int[] {
22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 10, 30 }, new int[] {
11, 33 });
d = b.addToHead(a);
assertEquals(d, c);
f = TrainPositionOnMap.createInstance(new int[] { 40, 50 }, new int[] {
44, 55 });
g = TrainPositionOnMap.createInstance(new int[] { 10, 30, 40 },
new int[] { 11, 33, 44 });
i = TrainPositionOnMap.createInstance(new int[] { 10, 30, 50 },
new int[] { 11, 33, 55 });
j = f.addToHead(g);
assertEquals(i, j);
}

RemoveTrainMove

Class: jfreerails.move.RemoveTrainMove

Documentation

No documentation available

Source Code

private RemoveTrainMove(Move[] moves) {
super(moves);
}

boundsContain

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

No documentation available

Source Code

boolean boundsContain(int x, int y);

Called Methods

No outgoing method calls

initComponents

Class: jfreerails.controller.CopyableTextJPanel

Documentation

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/

Source Code

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jPopupMenu1 = new javax.swing.JPopupMenu();
copyItem = new javax.swing.JMenuItem();
selectAllItem = new javax.swing.JMenuItem();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
copyItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK));
copyItem.setText("Copy");
copyItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
copyItemActionPerformed(evt);
}
});
jPopupMenu1.add(copyItem);
selectAllItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
selectAllItem.setText("Select All");
selectAllItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectAllItemActionPerformed(evt);
}
});
jPopupMenu1.add(selectAllItem);
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(500, 300));
jTextArea1.setEditable(false);
jTextArea1.setText("dsfasd\n\nsad\nf\nasd\nfa\nsdf\nas\ndf\nas\ndf\nads\nf\nasd\nf\nads\nf\ndsa\nf\ndsa\nf\ndasf\na\ndsf\nads\nf\nasd\nf\nasd\nf\n\nasdf");
jTextArea1.setWrapStyleWord(true);
jTextArea1.setOpaque(false);
jTextArea1.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTextArea1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTextArea1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}

initAutomaton

Class: jfreerails.server.TrainUpdater

Documentation

No documentation available

Source Code

public void initAutomaton(MoveReceiver mr) {
moveReceiver = mr;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.common.ImList

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImList))
return false;
final ImList imList = (ImList) o;
if (!Arrays.equals(elementData, imList.elementData))
return false;
return true;
}

Called Methods

No outgoing method calls

size

Class: jfreerails.server.CityEconomicModel

Documentation

No documentation available

Source Code

int size() {
return this.urbanTiles.size() + this.industryTiles.size()
+ this.resourceTiles.size();
}

Called Methods

No outgoing method calls

getName

Class: jfreerails.world.player.Player

Documentation

No documentation available

Source Code

public String getName() {
return name;
}

Called Methods

No outgoing method calls

GameLoop

Class: jfreerails.client.top.GameLoop

Documentation

No documentation available

Source Code

public GameLoop(ScreenHandler s, GameModel[] gm) {
screenHandler = s;
model = gm;
if (null == model) {
throw new NullPointerException();
}
}

Called Methods

No outgoing method calls

assertTryUndoMoveIsOk

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

protected void assertTryUndoMoveIsOk(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryUndoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals("First try failed", MoveStatus.MOVE_OK, ms);
ms = m.tryUndoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals(
"Second try failed, this suggests that the tryDoMove method failed to leave the world unchanged!",
MoveStatus.MOVE_OK, ms);
}

end_CannotBuildOnTheseTerrainTypes

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* A container element end event handling method.
*/

Source Code

/**
* A container element end event handling method.
*/
void end_CannotBuildOnTheseTerrainTypes() throws SAXException;

Called Methods

No outgoing method calls

isAlreadyASimilarPlayer

Class: jfreerails.move.AddPlayerMove

Documentation

No documentation available

Source Code

private boolean isAlreadyASimilarPlayer(World w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
Player pp = w.getPlayer(i);
if (pp.getName().equalsIgnoreCase(this.player2add.getName())) {
return true;
}
}
return false;
}

getTrackBooleanArray

Class: jfreerails.world.track.EightRotationsOfTrackPieceProducer

Documentation

No documentation available

Source Code

private static boolean[][] getTrackBooleanArray(int trackGraphicInt) {
boolean[][] trackBooleanArray = new boolean[3][3];
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
if (((trackGraphicInt >> (3 * y + x)) & 1) == 1) {
trackBooleanArray[x][y] = true;
}
}
}
return trackBooleanArray;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.move.AddItemToListMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = listKey.hashCode();
result = 29 * result + index;
result = 29 * result + principal.hashCode();
result = 29 * result + (item != null ? item.hashCode() : 0);
return result;
}

Called Methods

No outgoing method calls

canBuildStationHere

Class: jfreerails.client.view.StationBuildModel

Documentation

No documentation available

Source Code

public boolean canBuildStationHere() {
Point p = (Point) stationBuildAction
.getValue(StationBuildAction.STATION_POSITION_KEY);
return stationBuilder.tryBuildingStation(new ImPoint(p.x, p.y)).ok;
}

removeAllWagonsFromTrain

Class: jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest

Documentation

No documentation available

Source Code

private void removeAllWagonsFromTrain() {
addWagons(new ImInts());
}

setUp

Class: jfreerails.controller.SimpleAStarPathFinderTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() {
this.map = new Map();
pathFinder = new SimpleAStarPathFinder();
}

Called Methods

No outgoing method calls

nextInt

Class: jfreerails.controller.TrainPathIntIterator

Documentation

No documentation available

Source Code

public int nextInt() {
trackExplorer.nextEdge();
trackExplorer.moveForward();
return trackExplorer.getPosition();
}

checkPath

Class: jfreerails.world.train.PathOnTilesTest

Documentation

No documentation available

Source Code

private void checkPath(FreerailsPathIterator pathIt, ImPoint[] expected) {
IntLine line = new IntLine();
for (int i = 0; i < expected.length - 1; i++) {
assertTrue(pathIt.hasNext());
pathIt.nextSegment(line);
assertEquals(expected[i].x, line.x1);
assertEquals(expected[i + 1].x, line.x2);
assertEquals(expected[i].y, line.y1);
assertEquals(expected[i + 1].y, line.y2);
}
assertFalse(pathIt.hasNext());
}

upgradeTrackActionPerformed

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

No documentation available

Source Code

private void upgradeTrackActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_upgradeTrackActionPerformed
setVisible(true, true, false, false);
cancelStationPlacement();
setTrackBuilderMode(UPGRADE_TRACK);
}// GEN-LAST:event_upgradeTrackActionPerformed

currentTime

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

No documentation available

Source Code

GameTime currentTime();

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.view.TrainOrderJPanel

Documentation

No documentation available

Source Code

public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
this.w = mr.getWorld();
TrainListCellRenderer trainViewJPanel = (TrainListCellRenderer) consistChangeJPanel;
trainViewJPanel.setHeight(15);
trainViewJPanel.setup(mr, vl, null);
this.principal = mr.getPrincipal();
}

getSubclassesOf

Class: jfreerails.util.ClassLocater

Documentation

/**
* Find all instances of the given <code>Class</code> or interface by
* loading all classes on the class path.
* <P>
* Delegates to the other version, but passing in ".*" as the regex, i.e.
* "anything at all"
*
* @param targetType
* the superclass of all returned classes.
* @return an array of all subclasses of <code>targetType</code>
*/

Source Code

/**
* Find all instances of the given <code>Class</code> or interface by
* loading all classes on the class path.
* <P>
* Delegates to the other version, but passing in ".*" as the regex, i.e.
* "anything at all"
*
* @param targetType
* the superclass of all returned classes.
* @return an array of all subclasses of <code>targetType</code>
*/
public Class[] getSubclassesOf(Class targetType) {
return getSubclassesOf(targetType, ".*");
}

TrainRenderer

Class: jfreerails.client.renderer.TrainRenderer

Documentation

No documentation available

Source Code

public TrainRenderer(RenderersRoot trainImages) {
this.rr = trainImages;
}

Called Methods

No outgoing method calls

setRadius

Class: jfreerails.client.renderer.StationRadiusRenderer

Documentation

No documentation available

Source Code

public void setRadius(int radius) {
this.radius = radius;
}

Called Methods

No outgoing method calls

start_TrackType

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* A container element start event handling method.
*
* @param meta
* attributes
*/

Source Code

/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_TrackType(final Attributes meta) throws SAXException;

Called Methods

No outgoing method calls

toString

Class: jfreerails.move.CompositeMove

Documentation

No documentation available

Source Code

@Override
public final String toString() {
String s = "";
for (int i = 0; i < moves.size(); i++) {
s += moves.get(i).toString() + ((i > 0) ? ", " : "");
}
return s;
}

doneActionPerformed

Class: jfreerails.client.view.HtmlJPanel

Documentation

No documentation available

Source Code

private void doneActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_doneActionPerformed
// TODO add your handling code here:
}// GEN-LAST:event_doneActionPerformed

Called Methods

No outgoing method calls

getFixedCost

Class: jfreerails.world.track.TrackRuleProperties

Documentation

No documentation available

Source Code

public Money getFixedCost() {
return fixedCost;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.cargo.ImmutableCargoBundle

Documentation

No documentation available

Source Code

public static boolean equals(CargoBundle a, CargoBundle b) {
Iterator<CargoBatch> it = a.cargoBatchIterator();
if (a.size() != b.size())
return false;
while (it.hasNext()) {
CargoBatch batch = it.next();
if (a.getAmount(batch) != b.getAmount(batch)) {
return false;
}
}
return true;
}

StockPrice

Class: jfreerails.controller.StockPrice

Documentation

No documentation available

Source Code

public StockPrice(long netWorth, long profitLastyear, int publicShares, int otherRRShares){
currentPrice = calStockPrice(netWorth, profitLastyear, publicShares, otherRRShares);
sellPrice = calStockPrice(netWorth, profitLastyear, publicShares + STOCK_BUNDLE_SIZE, otherRRShares - STOCK_BUNDLE_SIZE);
buyPrice = calStockPrice(netWorth, profitLastyear, publicShares - STOCK_BUNDLE_SIZE, otherRRShares + STOCK_BUNDLE_SIZE);
treasurySellPrice = calStockPrice(netWorth, profitLastyear, publicShares + STOCK_BUNDLE_SIZE, otherRRShares);
treasuryBuyPrice = calStockPrice(netWorth, profitLastyear, publicShares - STOCK_BUNDLE_SIZE, otherRRShares);
}

isMinimised

Class: jfreerails.controller.ScreenHandler

Documentation

No documentation available

Source Code

public synchronized boolean isMinimised() {
return isMinimised;
}

Called Methods

No outgoing method calls

Consumption

Class: jfreerails.world.terrain.Consumption

Documentation

No documentation available

Source Code

public Consumption(int ct, int pq) {
cargoType = ct;
prerequisite = pq; // default value.
}

Called Methods

No outgoing method calls

showLeaderBoard

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showLeaderBoard() {
LeaderBoardJPanel leaderBoardJPanel = new LeaderBoardJPanel();
leaderBoardJPanel.setup(modelRoot, vl, closeCurrentDialogue);
showContent(leaderBoardJPanel);
}

cursorOneTileMove

Class: jfreerails.client.top.UserInputOnMapController

Documentation

No documentation available

Source Code

private void cursorOneTileMove(ImPoint oldPosition, Step vector) {
boolean b = (modelRoot.getProperty(ModelRoot.Property.CURSOR_MODE) == ModelRoot.Value.BUILD_TRACK_CURSOR_MODE);
if (null != trackBuilder && b) {
trackBuilder.setBuildTrackStrategy(getBts());
MoveStatus ms = trackBuilder.buildTrack(oldPosition, vector);
if (ms.ok) {
setCursorMessage("");
playAppropriateSound();
} else {
setCursorMessage(ms.message);
}
} else {
logger.warning("No track builder available!");
}
}

toString

Class: jfreerails.world.station.PlannedTrain

Documentation

No documentation available

Source Code

@Override
public String toString() {
return "engine type: " + this.engineType + ", with "
+ wagonTypes.size() + "wagons";
}

getNumberOfTransactions

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public int getNumberOfTransactions(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
return bankAccounts.sizeD2(playerIndex);
}

doPreMove

Class: jfreerails.controller.MoveExecutor

Documentation

No documentation available

Source Code

MoveStatus doPreMove(PreMove pm);

Called Methods

No outgoing method calls

moveCursorMoreTiles

Class: jfreerails.client.renderer.BuildTrackController

Documentation

/** Moves cursor which causes track to be built on the worldDiff object. */

Source Code

/** Moves cursor which causes track to be built on the worldDiff object. */
private void moveCursorMoreTiles(List<ImPoint> track) {
moveCursorMoreTiles(track, null);
}

TrainListCellRenderer

Class: jfreerails.client.view.TrainListCellRenderer

Documentation

No documentation available

Source Code

public TrainListCellRenderer(ModelRoot mr, RenderersRoot vl) {
setup(mr, vl, null);
this.setBackground(backgroundColor);
}

testThatAllTheFieldsDefinedInKEYAreInstancesOFKEY

Class: jfreerails.world.top.KEYTest

Documentation

No documentation available

Source Code

public void testThatAllTheFieldsDefinedInKEYAreInstancesOFKEY() {
Field[] fields = KEY.class.getFields();
for (int i = 0; i < fields.length; i++) {
String name = fields[i].getName();
int modifiers = fields[i].getModifiers();
if (!name.equals("shared")) {
assertTrue("All the fields of KEY should be static", Modifier
.isStatic(modifiers));
}
assertTrue("All the fields of KEY should be public", Modifier
.isPublic(modifiers));
assertTrue("All the fields of KEY should be final", Modifier
.isFinal(modifiers));
try {
if (Modifier.isStatic(modifiers)) {
Object o = fields[i].get(null);
assertTrue("All the fields of KEY should be instances of"
+ " KEY", o instanceof KEY);
}
} catch (IllegalAccessException e) {
assertTrue(false);
}
}
}

Called Methods

No outgoing method calls

componentHidden

Class: jfreerails.client.view.Unknown

Documentation

No documentation available

Source Code

@Override
public void componentHidden(ComponentEvent e) {
}

Called Methods

No outgoing method calls

processMove

Class: experimental.SimpleMoveReceiver

Documentation

No documentation available

Source Code

public void processMove(Move move) {
move.doMove(w, Player.AUTHORITATIVE);
}

uGet

Class: jfreerails.util.ListXDDiffs

Documentation

No documentation available

Source Code

abstract T uGet(int... i);

Called Methods

No outgoing method calls

getTrainRenderer

Class: jfreerails.client.view.OverHeadTrainView

Documentation

No documentation available

Source Code

public TrainRenderer getTrainRenderer() {
return trainRenderer;
}

Called Methods

No outgoing method calls

main

Class: jfreerails.move.ChangeTrackPieceCompositeMoveTest

Documentation

No documentation available

Source Code

public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}

setup

Class: jfreerails.client.view.SelectStationJPanel

Documentation

No documentation available

Source Code

public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
cargoWaitingAndDemandedJPanel1.setup(mr, vl, null);
this.world = mr.getWorld();
this.submitButtonCallBack = closeAction;
principal = mr.getPrincipal();
}

shutDownInput

Class: jfreerails.network.AbstractInetConnection

Documentation

No documentation available

Source Code

private synchronized void shutDownInput() {
try {
inetConnection.shutdownInput();
logger.fine(this + "Shut down input.");
if (status.isOpen()) {
shutdownOutput();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}

parse

Class: jfreerails.server.parser.CargoAndTerrainParser

Documentation

/**
* The recognizer entry method taking an Inputsource.
*
* @param input
* InputSource to be parsed.
* @throws java.io.IOException
* on I/O error.
* @throws SAXException
* propagated exception thrown by a DocumentHandler.
* @throws javax.xml.parsers.ParserConfigurationException
* a parser satisfying requested configuration can not be
* created.
*
*/

Source Code

/**
* The recognizer entry method taking an Inputsource.
*
* @param input
* InputSource to be parsed.
* @throws java.io.IOException
* on I/O error.
* @throws SAXException
* propagated exception thrown by a DocumentHandler.
* @throws javax.xml.parsers.ParserConfigurationException
* a parser satisfying requested configuration can not be
* created.
*
*/
public static void parse(final InputSource input,
final CargoAndTerrainHandler handler) throws SAXException,
javax.xml.parsers.ParserConfigurationException, java.io.IOException {
parse(input, new CargoAndTerrainParser(handler, null));
}

doMove

Class: jfreerails.move.RemoveItemFromListMove

Documentation

No documentation available

Source Code

public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.isOk()) {
w.set(principal, listKey, index, null);
}
return ms;
}

createTrainsJTabPane

Class: jfreerails.client.top.GUIComponentFactory

Documentation

No documentation available

Source Code

JTabbedPane createTrainsJTabPane();

Called Methods

No outgoing method calls

getX

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public int getX(int position) {
return xpoints.get(position);
}

StationBuildModel

Class: jfreerails.client.view.StationBuildModel

Documentation

No documentation available

Source Code

public StationBuildModel(StationBuilder sb, RenderersRoot rr, ModelRoot mr) {
stationBuilder = sb;
modelRoot = mr;
ReadOnlyWorld world = modelRoot.getWorld();
for (int i = 0; i < world.size(SKEY.TRACK_RULES); i++) {
final TrackRule trackRule = (TrackRule) world.get(
SKEY.TRACK_RULES, i);
if (trackRule.isStation()) {
TrackPieceRenderer renderer = rr.getTrackPieceView(i);
StationChooseAction action = new StationChooseAction(i);
String trackType = trackRule.getTypeName();
Money price = trackRule.getFixedCost();
String shortDescrpt = Utils.capitalizeEveryWord(trackType)
+ " $" + price.toString();
action.putValue(Action.SHORT_DESCRIPTION, shortDescrpt);
action.putValue(Action.NAME, "Build " + trackType);
action.putValue(Action.SMALL_ICON, new ImageIcon(renderer
.getTrackPieceIcon(trackTemplate)));
stationChooseActions.add(action);
id2Action.put(new Integer(i), action);
}
}
}

setTile

Class: jfreerails.world.top.World

Documentation

/**
* Replaces the tile at the specified position on the map with the specified
* tile.
*
*/

Source Code

/**
* Replaces the tile at the specified position on the map with the specified
* tile.
*
*/
void setTile(int x, int y, FreerailsSerializable tile);

Called Methods

No outgoing method calls

getUpdatedTiles

Class: jfreerails.move.RemoveStationMove

Documentation

No documentation available

Source Code

public Rectangle getUpdatedTiles() {
TrackMove tm = (TrackMove) getMove(0);
return tm.getUpdatedTiles();
}

equals

Class: jfreerails.world.cargo.ImmutableCargoBundle

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object arg0) {
if (null == arg0) {
return false;
}
if (!(arg0 instanceof CargoBundle)) {
return false;
}
return equals(this, (CargoBundle) arg0);
}

getEdgeCost

Class: jfreerails.controller.BuildTrackExplorer

Documentation

/**
* Calculates a cost figure incorporating the distance and the cost of any
* new track.
*/

Source Code

/**
* Calculates a cost figure incorporating the distance and the cost of any
* new track.
*/
public int getEdgeCost() {
if (beforeFirst) {
throw new IllegalStateException();
}
Step edgeDirection = Step.getInstance(directionInt - 1);
double length = edgeDirection.getLength();
final int DISTANCE_COST = 10000; // Same as the cost of standard
// track.
int cost = (int) Math.round(DISTANCE_COST * length);
if (!usingExistingTrack) {
int[] x = { currentPosition.getX(),
currentPosition.getX() + edgeDirection.deltaX };
int[] y = { currentPosition.getY(),
currentPosition.getY() + edgeDirection.deltaY };
TrackRule ruleA = getAppropriateTrackRule(x[0], y[0]);
TrackRule ruleB = getAppropriateTrackRule(x[1], y[1]);
/*
* If there is a station at either of the points, don't include its
* price in the cost calculation since it has already been paid.
* Otherwise, add the cost of building the track.
*/
long priceA = ruleA.getPrice().getAmount();
long priceB = ruleB.getPrice().getAmount();
cost += length * (priceA + priceB);
// Add fixed cost if tile b does not have the desired track type.
FreerailsTile a = (FreerailsTile) world.getTile(x[0], y[0]);
TrackRule currentRuleA = a.getTrackPiece().getTrackRule();
if (!currentRuleA.equals(ruleA)) {
assert (!currentRuleA.isStation()); // We shouldn't be upgrading
// a station.
cost += ruleA.getFixedCost().getAmount() * Step.TILE_DIAMETER;
}
}
return cost;
}

isTrainMoving

Class: jfreerails.controller.TrainStopsHandler

Documentation

No documentation available

Source Code

public boolean isTrainMoving() {
if (refreshWaitingForFullLoad()) {
return false;
}
GameTime time = worldDiffs.currentTime();
return time.getTicks() > this.timeLoadingFinished.getTicks();
}

testNextSegment

Class: jfreerails.world.train.SimplePathIteratorImplTest

Documentation

No documentation available

Source Code

public void testNextSegment() {
int[] xpoints = { 1, 2, 3 };
int[] ypoints = { 4, 5, 6 };
FreerailsPathIterator it = new SimplePathIteratorImpl(xpoints, ypoints);
assertTrue(it.hasNext());
IntLine line = new IntLine(0, 0, 0, 0);
it.nextSegment(line);
assertLineEquals(1, 4, 2, 5, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(2, 5, 3, 6, line);
assertTrue(!it.hasNext());
}

equals

Class: jfreerails.network.specifics.SetWorldMessage2Client

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof SetWorldMessage2Client))
return false;
final SetWorldMessage2Client setWorldMessage2Client = (SetWorldMessage2Client) o;
if (id != setWorldMessage2Client.id)
return false;
if (!world.equals(setWorldMessage2Client.world))
return false;
return true;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.common.GameTime

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return ticks;
}

Called Methods

No outgoing method calls

bHeadEqualsATail

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public static boolean bHeadEqualsATail(TrainPositionOnMap a,
TrainPositionOnMap b) {
return aHeadEqualsBTail(b, a);
}

getInstance

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

public static NullTrackType getInstance() {
return nullTrackType;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.move.NextActivityMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = activity.hashCode();
result = 29 * result + principal.hashCode();
result = 29 * result + index;
return result;
}

Called Methods

No outgoing method calls

getTransactionAndTimeStamp

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public Pair<Transaction, GameTime> getTransactionAndTimeStamp(
FreerailsPrincipal p, int i) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = bankAccounts.get(playerIndex, i);
return new Pair<Transaction, GameTime>(tats.getT(), tats.getTimeStamp());
}

testGetLength

Class: jfreerails.world.train.IntLineTest

Documentation

No documentation available

Source Code

public void testGetLength() {
IntLine line = new IntLine(0, 0, 100, 0);
assertEquals(100, line.getLength(), 0.1);
}

equals

Class: jfreerails.move.ChangeTileMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ChangeTileMove))
return false;
final ChangeTileMove changeTileMove = (ChangeTileMove) o;
if (x != changeTileMove.x)
return false;
if (y != changeTileMove.y)
return false;
if (!after.equals(changeTileMove.after))
return false;
if (!before.equals(changeTileMove.before))
return false;
return true;
}

reset

Class: jfreerails.world.top.WorldDiffs

Documentation

/**
* After this method returns, all differences are cleared and calls to
* methods on this object should produce the same results as calls the the
* corresponding methods on the underlying world object.
*/

Source Code

/**
* After this method returns, all differences are cleared and calls to
* methods on this object should produce the same results as calls the the
* corresponding methods on the underlying world object.
*/
public void reset() {
time = underlying.currentTime();
mapDiff.clear();
listDiff.clear();
}

testGetPossibleDirections

Class: jfreerails.controller.FlatTrackExplorerTest

Documentation

/**
* Tests that the track explorer at point 10,10 tells us that we can move
* west, east, or northeast.
*/

Source Code

/**
* Tests that the track explorer at point 10,10 tells us that we can move
* west, east, or northeast.
*/
public void testGetPossibleDirections() {
setUp();
FlatTrackExplorer fte;
PositionOnTrack p = PositionOnTrack.createComingFrom(10, 10,
Step.SOUTH_WEST);
fte = new FlatTrackExplorer(world, p);
// There should be 3 branches.
assertTrue(fte.hasNextEdge());
fte.nextEdge();
p.setValuesFromInt(fte.getVertexConnectedByEdge());
assertEquals(Step.EAST, p.cameFrom());
assertTrue(fte.hasNextEdge());
fte.nextEdge();
p.setValuesFromInt(fte.getVertexConnectedByEdge());
assertEquals(Step.WEST, p.cameFrom());
assertTrue(fte.hasNextEdge());
fte.nextEdge();
p.setValuesFromInt(fte.getVertexConnectedByEdge());
assertEquals(Step.NORTH_EAST, p.cameFrom());
assertTrue(!fte.hasNextEdge());
}

validate

Class: jfreerails.client.renderer.RenderersRoot

Documentation

No documentation available

Source Code

boolean validate(ReadOnlyWorld world);

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.train.WagonType

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object obj) {
if (!(obj instanceof WagonType))
return false;
WagonType other = (WagonType) obj;
return other.typeCategory == this.typeCategory
&& other.typeName.equals(typeName);
}

Called Methods

No outgoing method calls

discardValues

Class: jfreerails.util.GrowableBase

Documentation

/**
* Discards values for a range of indices in the array. Checks if the values
* stored in the array are object references, and if so clears them. If the
* values are primitives, this method does nothing.
*
* @param from
* index of first value to be discarded
* @param to
* index past last value to be discarded
*/

Source Code

/**
* Discards values for a range of indices in the array. Checks if the values
* stored in the array are object references, and if so clears them. If the
* values are primitives, this method does nothing.
*
* @param from
* index of first value to be discarded
* @param to
* index past last value to be discarded
*/
protected void discardValues(int from, int to) {
Object values = getArray();
if (!values.getClass().getComponentType().isPrimitive()) {
Object[] objects = (Object[]) values;
for (int i = from; i < to; i++) {
objects[i] = null;
}
}
}

addToTail

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public TrainPositionOnMap addToTail(TrainPositionOnMap a) {
TrainPositionOnMap b = this;
return addBtoHeadOfA(b, a);
}

main

Class: jfreerails.launcher.GUIClient

Documentation

No documentation available

Source Code

public static void main(String[] args) {
try {
GUIClient client = new GUIClient("Test", null,
ScreenHandler.WINDOWED_MODE, null);
client.start();
} catch (IOException e) {
e.printStackTrace();
}
}

initPositionStep1

Class: jfreerails.controller.AddTrainPreMove

Documentation

No documentation available

Source Code

PathOnTiles initPositionStep1(ReadOnlyWorld w) {
PositionOnTrack[] pp = FlatTrackExplorer.getPossiblePositions(w, point);
FlatTrackExplorer fte = new FlatTrackExplorer(w, pp[0]);
List<Step> steps = new ArrayList<Step>();
int length = calTrainLength();
int distanceTravelled = 0;
PositionOnTrack p = new PositionOnTrack();
while (distanceTravelled < length) {
fte.nextEdge();
fte.moveForward();
p.setValuesFromInt(fte.getPosition());
Step v = p.cameFrom();
distanceTravelled += v.getLength();
steps.add(v);
}
return new PathOnTiles(point, steps);
}

get

Class: jfreerails.util.List3D

Documentation

No documentation available

Source Code

T get(int d1, int d2, int d3);

Called Methods

No outgoing method calls

readResolve

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

private Object readResolve() throws ObjectStreamException {
return nullTrackType;
}

Called Methods

No outgoing method calls

getKey

Class: jfreerails.world.top.KEY

Documentation

No documentation available

Source Code

public static KEY getKey(int keyNum) {
return keys[keyNum];
}

Called Methods

No outgoing method calls

getPlayerName

Class: jfreerails.launcher.ClientOptionsJPanel

Documentation

No documentation available

Source Code

String getPlayerName() {
if (playerName.isVisible()) {
return playerName.getText();
}
int index = playerNames.getSelectedIndex();
if (index < 0)
return null; // no selection.
return names[index];
}

Called Methods

No outgoing method calls

isStationHere

Class: jfreerails.controller.TrackMoveProducer

Documentation

No documentation available

Source Code

private boolean isStationHere(ImPoint p) {
ReadOnlyWorld w = executor.getWorld();
FreerailsTile tile = (FreerailsTile) w.getTile(p.x, p.y);
return tile.getTrackPiece().getTrackRule().isStation();
}

loadAndUnloadCargo

Class: jfreerails.controller.TrainStopsHandler

Documentation

No documentation available

Source Code

void loadAndUnloadCargo(int stationId, boolean waiting, boolean autoConsist) {
// train is at a station so do the cargo processing
DropOffAndPickupCargoMoveGenerator transfer = new DropOffAndPickupCargoMoveGenerator(
trainId, stationId, worldDiffs, principal, waiting, autoConsist);
Move m = transfer.generateMove();
if(null != m){
MoveStatus ms = m.doMove(worldDiffs, principal);
if (!ms.ok)
throw new IllegalStateException(ms.message);
}
}

toArray

Class: jfreerails.util.IntArray

Documentation

/**
* Constructs and returns a simple array containing the same data as held in
* this growable array.
*
* @return array containing a copy of the data
*/

Source Code

/**
* Constructs and returns a simple array containing the same data as held in
* this growable array.
*
* @return array containing a copy of the data
*/
public int[] toArray() {
return (int[]) buildArray(int.class, 0, countPresent);
}

equals

Class: jfreerails.world.terrain.TileTypeImpl

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TileTypeImpl))
return false;
final TileTypeImpl tileType = (TileTypeImpl) o;
if (rgb != tileType.rgb)
return false;
if (rightOfWay != tileType.rightOfWay)
return false;
if (!consumption.equals(tileType.consumption))
return false;
if (!conversion.equals(tileType.conversion))
return false;
if (!production.equals(tileType.production))
return false;
if (!terrainCategory.equals(tileType.terrainCategory))
return false;
if (!terrainType.equals(tileType.terrainType))
return false;
if (tileBuildCost != null ? !tileBuildCost
.equals(tileType.tileBuildCost)
: tileType.tileBuildCost != null)
return false;
return true;
}

setUp

Class: jfreerails.move.TrackMoveTransactionsGeneratorTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
world = new WorldImpl(20, 20);
MapFixtureFactory.generateTrackRuleList(world);
player = new Player("test player", 0);
world.addPlayer(player);
transactionGenerator = new TrackMoveTransactionsGenerator(world, player
.getPrincipal());
}

createMainMap

Class: jfreerails.client.top.GUIComponentFactoryTestImpl

Documentation

No documentation available

Source Code

public JScrollPane createMainMap() {
return mainMapView;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.track.LegalTrackConfigurations

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = maximumConsecutivePieces;
result = 29 * result
+ (legalConfigs != null ? legalConfigs.hashCode() : 0);
return result;
}

getS

Class: jfreerails.world.train.ConstAcc

Documentation

No documentation available

Source Code

public double getS() {
return finalS;
}

Called Methods

No outgoing method calls

BrokerScreenHtmlJFrame

Class: jfreerails.client.view.BrokerScreenHtmlJFrame

Documentation

/** Creates a new instance of BrokerScreenHtmlJPanel */

Source Code

/** Creates a new instance of BrokerScreenHtmlJPanel */
public BrokerScreenHtmlJFrame() {
super();
URL url = BrokerScreenHtmlJFrame.class
.getResource("/jfreerails/client/view/Broker_Screen.html");
template = loadText(url);
this.setSize(550, 300);
}

open

Class: jfreerails.network.InetConnection

Documentation

/**
* Sets up the input and output streams, then sends the String
* "CONNECTION_OPEN" and attempts to read the same String back.
*/

Source Code

/**
* Sets up the input and output streams, then sends the String
* "CONNECTION_OPEN" and attempts to read the same String back.
*/
synchronized void open() throws IOException {
OutputStream outputStream = socket.getOutputStream();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
outputStream);
// deflaterOutputStream = new DeflaterOutputStream(outputStream);
// objectOutputStream = new ObjectOutputStream(deflaterOutputStream);
objectOutputStream = new ObjectOutputStream(bufferedOutputStream);
objectOutputStream.writeObject(CONNECTION_OPEN);
objectOutputStream.flush();
InputStream inputStream = socket.getInputStream();
// inflaterInputStream = new InflaterInputStream(inputStream);
// objectInputStream = new ObjectInputStream(inflaterInputStream);
objectInputStream = new ObjectInputStream(inputStream);
try {
String s = (String) objectInputStream.readObject();
if (!s.equals(CONNECTION_OPEN)) {
throw new IllegalStateException(s);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IOException(e.getMessage());
}
}

Called Methods

No outgoing method calls

createDateJLabel

Class: jfreerails.client.top.GUIComponentFactory

Documentation

No documentation available

Source Code

JLabel createDateJLabel();

Called Methods

No outgoing method calls

lengthenPath

Class: jfreerails.controller.TrainStopsHandler

Documentation

/** If wagons are added to a train, we need to increase its length.*/

Source Code

/** If wagons are added to a train, we need to increase its length.*/
static PathOnTiles lengthenPath(ReadOnlyWorld w, PathOnTiles path, int currentTrainLength) {
double pathDistance = path.getTotalDistance();
double extraDistanceNeeded = currentTrainLength - pathDistance;
List<Step> steps = new ArrayList<Step>();
ImPoint start = path.getStart();
Step firstStep = path.getStep(0);
PositionOnTrack nextPot = PositionOnTrack.createComingFrom(start.x, start.y, firstStep);
while( extraDistanceNeeded > 0){
FlatTrackExplorer fte = new FlatTrackExplorer(w, nextPot);
fte.nextEdge();
nextPot.setValuesFromInt(fte.getVertexConnectedByEdge());
Step cameFrom = nextPot.facing();
steps.add(0, cameFrom);
extraDistanceNeeded -= cameFrom.getLength();
}
//Add existing steps
for (int i = 0; i < path.steps(); i++) {
Step step = path.getStep(i);
steps.add(step);
}
ImPoint newStart = new ImPoint(nextPot.getX(), nextPot.getY());
path = new PathOnTiles(newStart, steps);
return path;
}

setProperty

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public void setProperty(Property p, Object newValue) {
Object oldValue = properties.get(p);
properties.put(p, newValue);
for (ModelRootListener listener : listeners) {
listener.propertyChange(p, oldValue, newValue);
}
}

equals

Class: jfreerails.world.top.GameRules

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object obj) {
if (!(obj instanceof GameRules)) {
return false;
}
GameRules test = (GameRules) obj;
return this.canConnect2OtherRRTrack == test.canConnect2OtherRRTrack
&& this.mustConnect2ExistingTrack == test.mustConnect2ExistingTrack;
}

Called Methods

No outgoing method calls

KEY

Class: jfreerails.world.top.KEY

Documentation

No documentation available

Source Code

private KEY() {
this.keyNumber = numberOfKeys;
keys[keyNumber] = this;
numberOfKeys++;
}

Called Methods

No outgoing method calls

getKey

Class: jfreerails.move.ListMove

Documentation

/**
* @return the type of object which was changed
*/

Source Code

/**
* @return the type of object which was changed
*/
KEY getKey();

Called Methods

No outgoing method calls

end_TrackPieceTemplate

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void end_TrackPieceTemplate() throws SAXException {
// do nothing.
}

Called Methods

No outgoing method calls

add

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public int add(FreerailsPrincipal p, KEY key, FreerailsSerializable element) {
int playerIndex = p.getWorldIndex();
return lists.addD3(playerIndex, key.getKeyID(), element);
}

updateHtml

Class: jfreerails.client.view.BrokerScreenHtmlJFrame

Documentation

No documentation available

Source Code

private void updateHtml() {
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal p = modelRoot.getPrincipal();
brokerScreenGenerator = new BrokerScreenGenerator(world, p);
// this is where the Menu get Enable and Disable by if you own any stock
// or if the TotalShares are 0
StringBuffer populatedTemplate = new StringBuffer();
populatedTemplate.append("<html>");
populatedTemplate
.append(populateTokens(template, brokerScreenGenerator));
for (int i = 0; i < world.getNumberOfPlayers(); i++) {
if (!(world.getPlayer(i).getPrincipal().equals(p))) {
BrokerScreenGenerator temp = new BrokerScreenGenerator(world,
world.getPlayer(i).getPrincipal());
populatedTemplate.append(populateTokens(template, temp));
}
}
populatedTemplate.append("</html>");
String html = populatedTemplate.toString();
setHtml(html);
enableAndDisableActions();
}

getAddIndex

Class: jfreerails.util.ArrayBase

Documentation

/**
* Gets the array offset for appending a value to those in the array. If the
* underlying array is full, it is grown by the appropriate size increment
* so that the index value returned is always valid for the array in use by
* the time of the return.
*
* @return index position for added element
*/

Source Code

/**
* Gets the array offset for appending a value to those in the array. If the
* underlying array is full, it is grown by the appropriate size increment
* so that the index value returned is always valid for the array in use by
* the time of the return.
*
* @return index position for added element
*/
protected final int getAddIndex() {
int index = countPresent++;
if (countPresent > countLimit) {
growArray(countPresent);
}
return index;
}

processTrainBundle

Class: jfreerails.controller.DropOffAndPickupCargoMoveGenerator

Documentation

No documentation available

Source Code

private void processTrainBundle() {
Iterator<CargoBatch> batches = trainAfter.toImmutableCargoBundle().cargoBatchIterator();
StationModel station = (StationModel) w.get(principal, KEY.STATIONS, stationId);
MutableCargoBundle cargoDroppedOff = new MutableCargoBundle();
// Unload the cargo that the station demands
while (batches.hasNext()) {
CargoBatch cb = batches.next();
// if the cargo is demanded and its not from this station
// originally...
Demand4Cargo demand = station.getDemand();
int cargoType = cb.getCargoType();
if ((demand.isCargoDemanded(cargoType)) && (stationId != cb.getStationOfOrigin())) {
int amount = trainAfter.getAmount(cb);
cargoDroppedOff.addCargo(cb, amount);
// Now perform any conversions..
ConvertedAtStation converted = station.getConverted();
if (converted.isCargoConverted(cargoType)) {
int newCargoType = converted.getConversion(cargoType);
CargoBatch newCargoBatch = new CargoBatch(newCargoType, station.x, station.y,
0, stationId);
stationAfter.addCargo(newCargoBatch, amount);
}
trainAfter.setAmount(cb, 0);
}
}
moves = ProcessCargoAtStationMoveGenerator.processCargo(w, cargoDroppedOff, this.stationId,
principal, trainId);
// Unload the cargo that there isn't space for on the train regardless
// of whether the station
// demands it.
ImInts spaceAvailable = train.spaceAvailable();
for (int cargoType = 0; cargoType < spaceAvailable.size(); cargoType++) {
int quantity = spaceAvailable.get(cargoType);
if (quantity < 0) {
int amount2transfer = -quantity;
transferCargo(cargoType, amount2transfer, trainAfter, stationAfter);
}
}
}

test2

Class: jfreerails.network.specifics.MovePrecommitterTest

Documentation

/** Test test clash. */

Source Code

/** Test test clash. */
public void test2() {
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
assertFalse(oldtime.equals(newTime));
Move m = new TimeTickMove(oldtime, newTime);
MoveStatus ms = m.tryDoMove(w, Player.AUTHORITATIVE);
assertTrue(ms.ok);
committer.toServer(m);
/* The move m should now have been precommitted. */
assertEquals(newTime, getTime());
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(1, committer.precomitted.size());
committer.fromServer(m);
assertFalse(m.tryDoMove(w, Player.AUTHORITATIVE).ok);
/* The move m should now be full committed. */
assertEquals(1, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
assertEquals(newTime, getTime());
committer.precommitMoves();
/*
* The committer should be block since the move on the uncommitted list
* fails to go through.
*/
assertTrue(committer.blocked);
assertEquals(1, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
Move m2 = new TimeTickMove(newTime, oldtime);
committer.fromServer(m2);
assertEquals(oldtime, getTime());
committer.fromServer(ms);
assertEquals(newTime, getTime());
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
}

getConsumption

Class: jfreerails.world.terrain.TerrainType

Documentation

No documentation available

Source Code

ImList<Consumption> getConsumption();

Called Methods

No outgoing method calls

loadNewTileViewList

Class: jfreerails.client.top.RenderersRootImpl

Documentation

No documentation available

Source Code

private TileRendererList loadNewTileViewList(ReadOnlyWorld w,
FreerailsProgressMonitor pm) throws IOException {
ArrayList<TileRenderer> tileRenderers = new ArrayList<TileRenderer>();
// Setup progress monitor..
int numberOfTypes = w.size(SKEY.TERRAIN_TYPES);
pm.nextStep(numberOfTypes);
int progress = 0;
pm.setValue(progress);
for (int i = 0; i < numberOfTypes; i++) {
TerrainType t = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
int[] typesTreatedAsTheSame = new int[] { i };
TileRenderer tr = null;
pm.setValue(++progress);
try {
// XXX hack to make rivers flow into ocean and habours & occean
// treat habours as the same type.
TerrainType.Category thisTerrainCategory = t.getCategory();
if (thisTerrainCategory.equals(TerrainType.Category.River)
|| thisTerrainCategory
.equals(TerrainType.Category.Ocean)) {
// Count number of types with category "water"
int count = 0;
for (int j = 0; j < numberOfTypes; j++) {
TerrainType t2 = (TerrainType) w.get(
SKEY.TERRAIN_TYPES, j);
TerrainType.Category terrainCategory = t2.getCategory();
if (terrainCategory.equals(TerrainType.Category.Ocean)
|| terrainCategory.equals(thisTerrainCategory)) {
count++;
}
}
typesTreatedAsTheSame = new int[count];
count = 0;
for (int j = 0; j < numberOfTypes; j++) {
TerrainType t2 = (TerrainType) w.get(
SKEY.TERRAIN_TYPES, j);
TerrainType.Category terrainCategory = t2.getCategory();
if (terrainCategory.equals(TerrainType.Category.Ocean)
|| terrainCategory.equals(thisTerrainCategory)) {
typesTreatedAsTheSame[count] = j;
count++;
}
}
}
tr = new RiverStyleTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io) {
}
try {
tr = new ForestStyleTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io) {
}
try {
tr = new ChequeredTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io) {
}
try {
tr = new StandardTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io) {
// If the image is missing, we generate it.
logger
.warning("No tile renderer for "
+ t.getTerrainTypeName());
String filename = StandardTileRenderer.generateFilename(t
.getTerrainTypeName());
Image image = QuickRGBTileRendererList.createImageFor(t);
imageManager.setImage(filename, image);
// generatedImages.setImage(filename, image);
try {
tr = new StandardTileRenderer(imageManager,
typesTreatedAsTheSame, t);
tileRenderers.add(tr);
continue;
} catch (IOException io2) {
io2.printStackTrace();
throw new IllegalStateException();
}
}
}
// XXXX add special tile renderer for habours
TileRenderer oceanTileRenderer = null;
for (int j = 0; j < numberOfTypes; j++) {
TerrainType t2 = (TerrainType) w.get(SKEY.TERRAIN_TYPES, j);
String terrainName = t2.getTerrainTypeName();
if (terrainName.equalsIgnoreCase("Ocean")) {
oceanTileRenderer = tileRenderers.get(j);
break;
}
}
for (int j = 0; j < numberOfTypes; j++) {
TerrainType t2 = (TerrainType) w.get(SKEY.TERRAIN_TYPES, j);
String terrainName = t2.getTerrainTypeName();
if (terrainName.equalsIgnoreCase("Harbour")) {
TerrainType t = (TerrainType) w.get(SKEY.TERRAIN_TYPES, j);
TileRenderer tr = new SpecialTileRenderer(imageManager,
new int[] { j }, t, oceanTileRenderer);
tileRenderers.set(j, tr);
break;
}
}
return new TileRendererListImpl(tileRenderers);
}

deltaAssets

Class: jfreerails.world.accounts.Receipt

Documentation

No documentation available

Source Code

public Money deltaAssets() {
return amount.changeSign();
}

isIgnoreKeyEvents

Class: jfreerails.client.top.UserInputOnMapController

Documentation

No documentation available

Source Code

private boolean isIgnoreKeyEvents() {
Boolean b = (Boolean) modelRoot.getProperty(Property.IGNORE_KEY_EVENTS);
return b.booleanValue();
}

suite

Class: jfreerails.world.track.LegalTrackConfigurationsTest

Documentation

No documentation available

Source Code

public static Test suite() {
return new TestSuite(LegalTrackConfigurationsTest.class);
}

Called Methods

No outgoing method calls

setSelectedItem

Class: jfreerails.client.common.ActionAdapter

Documentation

/**
* @param item
* The NAME of the Action selected
*/

Source Code

/**
* @param item
* The NAME of the Action selected
*/
@Override
public void setSelectedItem(Object item) {
// only set the item if not already selected
if ((item != null) && item.equals(getSelectedItem())) {
return;
}
super.setSelectedItem(item);
// stop addElement from triggering actions
if (!initialised) {
return;
}
for (int i = 0; i < buttonModels.size(); i++) {
MappedButtonModel bm = buttonModels.get(i);
if (bm.actionName.equals(item)) {
bm.setSelected(true);
}
}
if (performActionOnSetSelectedItem) {
for (int i = 0; i < actions.length; i++) {
if (actions[i].getValue(Action.NAME).equals(item)) {
actions[i].actionPerformed(new ActionEvent(this,
ActionEvent.ACTION_PERFORMED, (String) actions[i]
.getValue(Action.ACTION_COMMAND_KEY)));
}
}
}
}

Called Methods

  • jfreerails.client.common.ActionAdapter.MappedButtonModel.setSelected (external)

List2DImpl

Class: jfreerails.util.List2DImpl

Documentation

No documentation available

Source Code

public List2DImpl(int d1){
for(int i = 0; i < d1; i++){
elementData.add(new ArrayList<T>());
}
}

Called Methods

No outgoing method calls

main

Class: experimental.TrainMotionExpt

Documentation

No documentation available

Source Code

public static void main(String[] args) {
System.setProperty("SHOWFPS", "true");
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.getContentPane().add(new TrainMotionExpt());
ScreenHandler screenHandler = new ScreenHandler(f,
ScreenHandler.WINDOWED_MODE);
screenHandler.apply();
GameLoop gameLoop = new GameLoop(screenHandler);
Thread t = new Thread(gameLoop);
t.start();
}

testAddIntArray

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.ListXDDiffs.add(int...)'
*/
public void testAddIntArray() {
assertEquals(0, diffs.sizeD1());
diffs.addDimension();
ListKey sizeKey = new ListKey(EndPoint, listid.test);
assertEquals("There should be two values: EndPoint = 0 and EndPoint[0] = 0", 2, map.size());
assertTrue(map.containsKey(sizeKey));
assertEquals(new Integer(1), map.get(sizeKey));
assertEquals(1, diffs.sizeD1());
assertEquals(0, diffs.sizeD2(0));
diffs.addDimension(0);
assertEquals(1, diffs.sizeD2(0));
}

hashCode

Class: jfreerails.controller.OpenListEntry

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = f;
result = 29 * result + node;
return result;
}

Called Methods

No outgoing method calls

NullTerrainType

Class: jfreerails.world.terrain.NullTerrainType

Documentation

No documentation available

Source Code

private NullTerrainType() {
}

Called Methods

No outgoing method calls

tryBuildingStation

Class: jfreerails.controller.StationBuilder

Documentation

No documentation available

Source Code

public MoveStatus tryBuildingStation(ImPoint p) {
ReadOnlyWorld world = executor.getWorld();
FreerailsPrincipal principal = executor.getPrincipal();
AddStationPreMove preMove = AddStationPreMove.newStation(p,
this.ruleNumber, principal);
Move m = preMove.generateMove(world);
MoveStatus ms = executor.tryDoMove(m);
return ms;
}

end_CanOnlyBuildOnTheseTerrainTypes

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* A container element end event handling method.
*/

Source Code

/**
* A container element end event handling method.
*/
void end_CanOnlyBuildOnTheseTerrainTypes() throws SAXException;

Called Methods

No outgoing method calls

getUnderlyingSize

Class: jfreerails.util.List2DDiff

Documentation

No documentation available

Source Code

@Override
int getUnderlyingSize(int... dim) {
if(dim.length == 0)
return underlyingList.sizeD1();
if(dim.length == 1){
if (underlyingList.sizeD1() <= dim[0])
return -1;
return underlyingList.sizeD2(dim[0]);
}
throw new IllegalArgumentException(String.valueOf(dim.length));
}

getBefore

Class: jfreerails.move.ListMove

Documentation

/**
* @return the old item or null if not any.
*/

Source Code

/**
* @return the old item or null if not any.
*/
FreerailsSerializable getBefore();

Called Methods

No outgoing method calls

equals

Class: jfreerails.controller.AddTrainPreMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof AddTrainPreMove)) {
return false;
}
final AddTrainPreMove addTrainPreMove = (AddTrainPreMove) o;
if (engineTypeId != addTrainPreMove.engineTypeId) {
return false;
}
if (!point.equals(addTrainPreMove.point)) {
return false;
}
if (!principal.equals(addTrainPreMove.principal)) {
return false;
}
if (!schedule.equals(addTrainPreMove.schedule)) {
return false;
}
if (!wagons.equals(addTrainPreMove.wagons)) {
return false;
}
return true;
}

setRepaintOffAndDisableDoubleBuffering

Class: jfreerails.controller.ScreenHandler

Documentation

No documentation available

Source Code

private static void setRepaintOffAndDisableDoubleBuffering(Component c) {
c.setIgnoreRepaint(true);
// Since we are using a buffer strategy we don't want Swing
// to double buffer any JComponents.
if (c instanceof JComponent) {
JComponent jComponent = (JComponent) c;
jComponent.setDoubleBuffered(false);
}
if (c instanceof java.awt.Container) {
Component[] children = ((Container) c).getComponents();
for (int i = 0; i < children.length; i++) {
setRepaintOffAndDisableDoubleBuffering(children[i]);
}
}
}

setSelectedItem

Class: jfreerails.client.view.DisplayModesComboBoxModels

Documentation

No documentation available

Source Code

public void setSelectedItem(Object anItem) {
selection = (MyDisplayMode) anItem;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = x;
result = 29 * result + y;
result = 29 * result + cameFrom.hashCode();
return result;
}

Called Methods

No outgoing method calls

orderHasWagons

Class: jfreerails.world.train.TrainOrdersModel

Documentation

No documentation available

Source Code

public boolean orderHasWagons() {
return null != consist && 0 != consist.size();
}

TrainListJPanel

Class: jfreerails.client.view.TrainListJPanel

Documentation

No documentation available

Source Code

public TrainListJPanel(boolean isInRHSJTabPane) {
this();
rhsjTabPane = isInRHSJTabPane;
}

setTile

Class: jfreerails.server.MapFactory

Documentation

No documentation available

Source Code

private static void setTile(int x, int y, FreerailsTile tile) {
if (!non_countryTypes.contains(new Integer(((FreerailsTile) world
.getTile(x, y)).getTerrainTypeID()))) {
world.setTile(x, y, tile);
}
}

removeUpdate

Class: jfreerails.launcher.Unknown

Documentation

No documentation available

Source Code

public void removeUpdate(DocumentEvent e) {
validateInput();
}

addCargo

Class: jfreerails.world.cargo.MutableCargoBundle

Documentation

No documentation available

Source Code

public void addCargo(CargoBatch cb, int amount) {
int amountAlready = this.getAmount(cb);
this.setAmount(cb, amount + amountAlready);
updateID++;
}

issueBond

Class: jfreerails.world.accounts.BondTransaction

Documentation

No documentation available

Source Code

public static BondTransaction issueBond(int interestRate) {
return new BondTransaction(Category.BOND, interestRate, 1,
BOND_VALUE_ISSUE);
}

Called Methods

No outgoing method calls

isAutoConsist

Class: jfreerails.world.train.TrainOrdersModel

Documentation

No documentation available

Source Code

public boolean isAutoConsist() {
return autoConsist;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.move.UndoMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof UndoMove))
return false;
final UndoMove undoMove = (UndoMove) o;
if (!move2undo.equals(undoMove.move2undo))
return false;
return true;
}

Called Methods

No outgoing method calls

generateFileNameNumber

Class: jfreerails.client.renderer.ForestStyleTileRenderer

Documentation

No documentation available

Source Code

@Override
protected String generateFileNameNumber(int i) {
return BinaryNumberFormatter.format(i, 2);
}

formKeyPressed

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

No documentation available

Source Code

private void formKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_formKeyPressed
viewMode.doClick();
}// GEN-LAST:event_formKeyPressed

Called Methods

No outgoing method calls

getActivities

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public ActivityIterator getActivities(final FreerailsPrincipal p, int index) {
final int playerIndex = p.getWorldIndex();
return new ActivityIteratorImpl(playerIndex, index);
}

getWorld

Class: jfreerails.controller.FlatTrackExplorer

Documentation

No documentation available

Source Code

public ReadOnlyWorld getWorld() {
return w;
}

Called Methods

No outgoing method calls

getNextScheduledOrder

Class: jfreerails.world.train.ImmutableSchedule

Documentation

No documentation available

Source Code

public int getNextScheduledOrder() {
return this.nextScheduledOrder;
}

Called Methods

No outgoing method calls

Production

Class: jfreerails.world.terrain.Production

Documentation

No documentation available

Source Code

public Production(int type, int r) {
cargoType = type;
rate = r;
}

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.common.ModelRootImpl

Documentation

/**
* Updates the ModelRoot with those properties which are dependent upon the
* world model. Call this when the world model is changed (e.g. new map is
* loaded)
*/

Source Code

/**
* Updates the ModelRoot with those properties which are dependent upon the
* world model. Call this when the world model is changed (e.g. new map is
* loaded)
*/
public void setup(ReadOnlyWorld world, FreerailsPrincipal p) {
this.world = world;
assert p != null;
assert world.isPlayer(p);
playerPrincipal = p;
if (null == world) {
throw new NullPointerException();
}
BuildTrackStrategy bts = BuildTrackStrategy.getDefault(world);
setProperty(ModelRoot.Property.BUILD_TRACK_STRATEGY, bts);
hasBeenSetup = true;
}

setUp

Class: jfreerails.util.ListXDTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
list1d = new List1DImpl<Object>();
list2d = new List2DImpl<Object>(5);
list3d = new List3DImpl<Object>(3, 2);
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.common.ImSet

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImSet))
return false;
final ImSet imSet = (ImSet) o;
if (!hashSet.equals(imSet.hashSet))
return false;
return true;
}

Called Methods

No outgoing method calls

getLocation

Class: jfreerails.world.terrain.CityModel

Documentation

No documentation available

Source Code

public ImPoint getLocation(){
return new ImPoint(x, y);
}

Called Methods

No outgoing method calls

getScrollableBlockIncrement

Class: jfreerails.client.view.MapViewJComponent

Documentation

No documentation available

Source Code

public int getScrollableBlockIncrement(java.awt.Rectangle rectangle,
int orientation, int direction) {
if (javax.swing.SwingConstants.VERTICAL == orientation) {
int best = (int) (((rectangle.height / getMapView().getScale()) - 2) * getMapView()
.getScale());
if (best > 0) {
return best;
}
return rectangle.height;
}
float f = ((rectangle.width / getMapView().getScale()) - 2)
* getMapView().getScale();
int best = (int) (f);
if (best > 0) {
return best;
}
return rectangle.width;
}

testEquals

Class: jfreerails.world.top.WorldDiffsTest

Documentation

No documentation available

Source Code

public void testEquals(){
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
WorldDiffs a = new WorldDiffs(underlyingWorld);
WorldDiffs b = new WorldDiffs(underlyingWorld);
assertEquals(a, a);
assertEquals(a, b);
assertEquals(a, underlyingWorld);
assertEquals(underlyingWorld, a);
}

equals

Class: jfreerails.network.specifics.SetPropertyMessage2Client

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof SetPropertyMessage2Client))
return false;
final SetPropertyMessage2Client setPropertyMessage2Client = (SetPropertyMessage2Client) o;
if (id != setPropertyMessage2Client.id)
return false;
if (!key.equals(setPropertyMessage2Client.key))
return false;
if (!value.equals(setPropertyMessage2Client.value))
return false;
return true;
}

Called Methods

No outgoing method calls

getAfter

Class: jfreerails.move.ChangeItemInListMove

Documentation

No documentation available

Source Code

public FreerailsSerializable getAfter() {
return after;
}

Called Methods

No outgoing method calls

set

Class: jfreerails.util.List1D

Documentation

No documentation available

Source Code

void set(int i, T element);

Called Methods

No outgoing method calls

contains

Class: jfreerails.world.track.TrackConfiguration

Documentation

No documentation available

Source Code

public boolean contains(int trackTemplate) {
if ((trackTemplate | this.configuration) == this.configuration) {
return true;
}
return false;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.move.ChangeItemInListMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = listKey.hashCode();
result = 29 * result + index;
result = 29 * result + (before != null ? before.hashCode() : 0);
result = 29 * result + (after != null ? after.hashCode() : 0);
result = 29 * result + principal.hashCode();
return result;
}

Called Methods

No outgoing method calls

getYPoints

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public ImInts getYPoints() {
return ypoints;
}

Called Methods

No outgoing method calls

assertLineEquals

Class: jfreerails.world.train.SimplePathIteratorImplTest

Documentation

No documentation available

Source Code

private void assertLineEquals(int x1, int y1, int x2, int y2, IntLine line) {
assertEquals(x1, line.x1);
assertEquals(x2, line.x2);
assertEquals(y1, line.y1);
assertEquals(y2, line.y2);
}

Called Methods

No outgoing method calls

testSubtract

Class: jfreerails.world.track.TrackConfigurationTest

Documentation

No documentation available

Source Code

public void testSubtract() {
TrackConfiguration a = TrackConfiguration.getFlatInstance("100010000");
TrackConfiguration b = TrackConfiguration.subtract(a, Step.NORTH_WEST);
assertEquals(TrackConfiguration.getFlatInstance("000010000"), b);
}

isStation

Class: jfreerails.world.track.TrackRuleProperties

Documentation

No documentation available

Source Code

public boolean isStation() {
return category.equals(TrackRule.TrackCategories.station);
}

Called Methods

No outgoing method calls

testBuildingOneTrackPiece

Class: jfreerails.controller.TrackBuildingTest

Documentation

/** Tests building track from 5,5 to 6,5 */

Source Code

/** Tests building track from 5,5 to 6,5 */
public void testBuildingOneTrackPiece() {
ImPoint from = new ImPoint(5, 5);
ImPoint to = new ImPoint(6, 5);
try {
// Check there is no track before we build it.
TrackPiece tp1 = ((FreerailsTile) w.getTile(5, 5)).getTrackPiece();
assertEquals(NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER, tp1
.getTrackTypeID());
TrackPiece tp2 = ((FreerailsTile) w.getTile(6, 5)).getTrackPiece();
assertEquals(NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER, tp2
.getTrackTypeID());
pathFinder.setupSearch(from, to, bts);
pathFinder.search(-1);
assertEquals(pathFinder.getStatus(),
IncrementalPathFinder.PATH_FOUND);
Step[] path = pathFinder.pathAsVectors();
assertEquals(path.length, 1);
assertEquals(Step.EAST, path[0]);
MoveStatus ms = producer.buildTrack(from, path);
assertTrue(ms.message, ms.ok);
// Check track has been built.
tp1 = ((FreerailsTile) w.getTile(5, 5)).getTrackPiece();
assertEquals(0, tp1.getTrackTypeID());
tp2 = ((FreerailsTile) w.getTile(6, 5)).getTrackPiece();
assertEquals(0, tp2.getTrackTypeID());
} catch (PathNotFoundException e) {
fail();
}
}

validate

Class: jfreerails.client.renderer.MyRenderersRoot

Documentation

No documentation available

Source Code

@Override
public boolean validate(ReadOnlyWorld world) {
throw new UnsupportedOperationException("Not supported yet.");
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.move.ChangeItemInListMove

Documentation

No documentation available

Source Code

@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(getClass().getName());
sb.append(" before: ");
sb.append(before.toString());
sb.append(" after: ");
sb.append(after.toString());
return sb.toString();
}

Called Methods

No outgoing method calls

start_Terrain_Types

Class: jfreerails.server.parser.CargoAndTerrainHandlerImpl

Documentation

No documentation available

Source Code

public void start_Terrain_Types(final Attributes meta) throws SAXException {
// no need to do anything here.
}

Called Methods

No outgoing method calls

IntArray

Class: jfreerails.util.IntArray

Documentation

/**
* Default constructor.
*/

Source Code

/**
* Default constructor.
*/
public IntArray() {
this(DEFAULT_SIZE);
}

getMaxSpeed

Class: jfreerails.world.train.EngineType

Documentation

No documentation available

Source Code

public int getMaxSpeed() {
return maxSpeed;
}

Called Methods

No outgoing method calls

paintComponent

Class: jfreerails.client.view.OverviewMapJComponent

Documentation

No documentation available

Source Code

@Override
protected void paintComponent(java.awt.Graphics g) {
java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
java.awt.Rectangle r = this.getVisibleRect();
mapView.paintRect(g2, r);
g2.setColor(Color.WHITE);
g2.drawRect(mainMapVisRect.x, mainMapVisRect.y, mainMapVisRect.width,
mainMapVisRect.height);
}

accept

Class: jfreerails.server.SavFileFilter

Documentation

No documentation available

Source Code

public boolean accept(File dir, String name) {
return (name.endsWith(".sav"));
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.common.IntLine

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = x1;
result = 29 * result + x2;
result = 29 * result + y1;
result = 29 * result + y2;
return result;
}

Called Methods

No outgoing method calls

getChangeOnTrain

Class: jfreerails.move.TransferCargoAtStationMove

Documentation

No documentation available

Source Code

public ChangeCargoBundleMove getChangeOnTrain() {
return (ChangeCargoBundleMove) super.getMoves().get(
CHANGE_ON_TRAIN_INDEX);
}

setBuildMode

Class: jfreerails.controller.TrackMoveProducer

Documentation

No documentation available

Source Code

public void setBuildMode(BuildMode buildMode) {
mr.setProperty(Property.TRACK_BUILDER_MODE, buildMode);
}

display

Class: jfreerails.client.view.CargoWaitingAndDemandedJPanel

Documentation

No documentation available

Source Code

public void display(int newStationID) {
StationModel station = (StationModel) world.get(principal,
KEY.STATIONS, newStationID);
this.stationName.setText(station.getStationName());
final ImmutableCargoBundle cargoWaiting = (ImmutableCargoBundle) world
.get(principal, KEY.CARGO_BUNDLES, station.getCargoBundleID());
// count the number of cargo types waiting and demanded.
final ArrayList<String> typeWaiting = new ArrayList<String>();
final ArrayList<Integer> quantityWaiting = new ArrayList<Integer>();
final Vector<String> typeDemanded = new Vector<String>();
for (int i = 0; i < world.size(SKEY.CARGO_TYPES); i++) {
CargoType cargoType = (CargoType) world.get(SKEY.CARGO_TYPES, i);
int amountWaiting = cargoWaiting.getAmount(i);
if (0 != amountWaiting) {
typeWaiting.add(cargoType.getDisplayName());
int carloads = amountWaiting
/ WagonType.UNITS_OF_CARGO_PER_WAGON;
quantityWaiting.add(new Integer(carloads));
}
if (station.getDemand().isCargoDemanded(i)) {
typeDemanded.add(cargoType.getDisplayName());
}
}
/*
* The table shows the cargo waiting at the station. First column is
* cargo type; second column is quantity in carloads.
*/
TableModel tableModel = new AbstractTableModel() {
private static final long serialVersionUID = 3760559784860071476L;
public int getRowCount() {
return typeWaiting.size();
}
public int getColumnCount() {
return 2;
}
public Object getValueAt(int row, int column) {
if (0 == column) {
return typeWaiting.get(row);
}
return quantityWaiting.get(row);
}
};
this.waitingJTable.setModel(tableModel);
/* The list shows the cargo demanded by the station. */
this.demandsJList.setListData(typeDemanded);
this.invalidate();
}

TrainStopsHandler

Class: jfreerails.controller.TrainStopsHandler

Documentation

No documentation available

Source Code

public TrainStopsHandler(int id, FreerailsPrincipal p, WorldDiffs w) {
trainId = id;
principal = p;
worldDiffs = w;
}

Called Methods

No outgoing method calls

nextSegment

Class: jfreerails.world.train.TrainPathIterator

Documentation

No documentation available

Source Code

public void nextSegment(IntLine line) {
p1.setValuesFromInt(p2.toInt());
line.x1 = p1.getX() * tileSize + tileSize / 2;
line.y1 = p1.getY() * tileSize + tileSize / 2;
p2.setValuesFromInt(intIterator.nextInt());
line.x2 = p2.getX() * tileSize + tileSize / 2;
line.y2 = p2.getY() * tileSize + tileSize / 2;
}

NewGameAction

Class: jfreerails.client.view.NewGameAction

Documentation

No documentation available

Source Code

public NewGameAction(String s) {
if (s == null) {
putValue(NAME, "New Game...");
} else {
putValue(NAME, s);
putValue(ACTION_COMMAND_KEY, s);
}
}

Called Methods

No outgoing method calls

incrementRunningTotal

Class: jfreerails.controller.FinancialDataGatherer

Documentation

No documentation available

Source Code

@Override
protected void incrementRunningTotal(int transactionID) {
Transaction t = super.w.getTransaction(super.principal, transactionID);
if (t instanceof AddItemTransaction) {
AddItemTransaction ait = (AddItemTransaction) t;
if (t instanceof StockTransaction
&& ait.getCategory() == Transaction.Category.ISSUE_STOCK
&& ait.getType() == -1) {
// If it is a change in the total number of shares issued.
StockTransaction ist = (StockTransaction) t;
totalShares += ist.getQuantity();
} else if (t instanceof StockTransaction
&& ait.getCategory() == Transaction.Category.TRANSFER_STOCK
) {
//
stockInRRs[ait.getType()] += ait.getQuantity();
} else if (t instanceof BondTransaction) {
bonds += ait.getQuantity();
}
} else {
super.incrementRunningTotal(transactionID);
}
}

set

Class: jfreerails.world.top.World

Documentation

/**
* Replaces the element at the specified position in the specified list with
* the specified element.
*
*/

Source Code

/**
* Replaces the element at the specified position in the specified list with
* the specified element.
*
*/
void set(SKEY key, int index, FreerailsSerializable element);

Called Methods

No outgoing method calls

getFinishTime

Class: jfreerails.world.common.ActivityIterator

Documentation

/** Returns the time the current activity ends. */

Source Code

/** Returns the time the current activity ends. */
double getFinishTime();

Called Methods

No outgoing method calls

isCargoDemanded

Class: jfreerails.world.station.Demand4Cargo

Documentation

No documentation available

Source Code

public boolean isCargoDemanded(int cargoNumber) {
return demand.get(cargoNumber) == 1;
}

OpenList

Class: jfreerails.controller.OpenList

Documentation

No documentation available

Source Code

public OpenList() {
}

Called Methods

No outgoing method calls

getMapSizeInPixels

Class: jfreerails.client.view.MapViewJComponent

Documentation

No documentation available

Source Code

public Dimension getMapSizeInPixels() {
return getMapView().getMapSizeInPixels();
}

ForestStyleTileRenderer

Class: jfreerails.client.renderer.ForestStyleTileRenderer

Documentation

No documentation available

Source Code

public ForestStyleTileRenderer(ImageManager imageManager, int[] rgbValues,
TerrainType tileModel) throws IOException {
super(tileModel, rgbValues);
this.setTileIcons(new Image[4]);
for (int i = 0; i < this.getTileIcons().length; i++) {
String fileName = generateRelativeFileName(i);
this.getTileIcons()[i] = imageManager.getImage(fileName);
}
}

setInitialTrainPosition

Class: jfreerails.server.TrainUpdater

Documentation

No documentation available

Source Code

static TrainPositionOnMap setInitialTrainPosition(TrainModel train,
FreerailsPathIterator from) {
int trainLength = train.getLength();
PathWalker fromPathWalker = new PathWalkerImpl(from);
assert fromPathWalker.canStepForward();
fromPathWalker.stepForward(trainLength);
TrainPositionOnMap initialPosition = TrainPositionOnMap
.createInSameDirectionAsPath(fromPathWalker);
return initialPosition;
}

getTimes

Class: jfreerails.world.top.TransactionAggregator

Documentation

No documentation available

Source Code

public GameTime[] getTimes() {
// return defensive copy.
return timeValues.clone();
}

Called Methods

  • _Dummy_.__Array__.clone (external)

UserMessageGenerator

Class: jfreerails.client.top.UserMessageGenerator

Documentation

No documentation available

Source Code

public UserMessageGenerator(ModelRoot mr, ActionRoot actionRoot) {
if (null == mr || null == actionRoot) {
throw new NullPointerException();
}
this.actionRoot = actionRoot;
this.modelRoot = mr;
}

Called Methods

No outgoing method calls

SaveGameAction

Class: jfreerails.client.view.SaveGameAction

Documentation

No documentation available

Source Code

public SaveGameAction() {
putValue(NAME, "Save Game");
putValue(MNEMONIC_KEY, new Integer(83));
}

Called Methods

No outgoing method calls

getSize

Class: jfreerails.client.view.DisplayModesComboBoxModels

Documentation

No documentation available

Source Code

public int getSize() {
return modes.size();
}

Called Methods

No outgoing method calls

removeLast

Class: jfreerails.world.top.World

Documentation

/**
* Removes the last element from the specified list.
*
*/

Source Code

/**
* Removes the last element from the specified list.
*
*/
FreerailsSerializable removeLast(SKEY key);

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.train.TrainModel

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object obj) {
if (obj instanceof TrainModel) {
TrainModel test = (TrainModel) obj;
boolean b = this.cargoBundleId == test.cargoBundleId
&& this.engineTypeId == test.engineTypeId
&& this.wagonTypes.equals(test.wagonTypes)
&& this.scheduleId == test.scheduleId;
return b;
}
return false;
}

assertOkButNotRepeatable

Class: jfreerails.move.AbstractMoveTestCase

Documentation

/**
* Generally moves should not be repeatable. For example, if we have just
* removed a piece of track, that piece of track is gone, so we cannot
* remove it again.
*/

Source Code

/**
* Generally moves should not be repeatable. For example, if we have just
* removed a piece of track, that piece of track is gone, so we cannot
* remove it again.
*/
protected void assertOkButNotRepeatable(Move m) {
assertSetupHasBeenCalled();
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
assertTryMoveFails(m);
assertDoMoveFails(m);
assertTryUndoMoveIsOk(m);
assertUndoMoveIsOk(m);
assertTryUndoMoveFails(m);
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
}

addIndustryTile

Class: jfreerails.server.CityTilePositioner

Documentation

No documentation available

Source Code

private void addIndustryTile(CityEconomicModel city) {
int size = city.industriesNotAtCity.size();
if (size > 0) {
int tileTypeNo = random.nextInt(size);
TerrainType type = city.industriesNotAtCity.get(tileTypeNo);
city.addTile(type);
}
}

testWithEmptySchedule

Class: jfreerails.controller.TrainStopsHandlerTest

Documentation

/**
A train can have an empty schedule if all stops are removed from the
* schedule or all the stations on the schedule are bulldozed.
*
* See bug #199 Unexpected Exception: null line -1
*/

Source Code

/**
A train can have an empty schedule if all stops are removed from the
* schedule or all the stations on the schedule are bulldozed.
*
* See bug #199 Unexpected Exception: null line -1
*/
@Test
public void testWithEmptySchedule() {
FreerailsPrincipal principal = w.getPlayer(0).getPrincipal();
assertEquals(2, w.size(principal, KEY.STATIONS));
assertEquals(1, w.size(principal, KEY.TRAINS));
WorldDiffs diffs = new WorldDiffs(w);
TrainStopsHandler tsh = new TrainStopsHandler(0, principal, diffs);
assertFalse(tsh.isWaiting4FullLoad());
ImmutableSchedule schedule = new MutableSchedule().toImmutableSchedule();
w.set(principal, KEY.TRAIN_SCHEDULES, 0, schedule);
boolean waiting4FullLoad = tsh.isWaiting4FullLoad();
assertFalse(waiting4FullLoad);
}

toString

Class: jfreerails.world.track.TrackConfiguration

Documentation

/**
* Returns a String representing this configuration, for example "north,
* south".
*/

Source Code

/**
* Returns a String representing this configuration, for example "north,
* south".
*/
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
int matches = 0;
if (contains(TrackConfiguration.getFlatInstance("000010000"))) {
sb.append("tile center");
} else {
sb.append("no tile center");
}
for (int i = 0; i < 8; i++) {
Step v = Step.getInstance(i);
if (contains(v)) {
sb.append(",");
sb.append(v);
matches++;
}
}
return sb.toString().trim();
}

getNumberOfCategories

Class: jfreerails.world.cargo.CargoType

Documentation

No documentation available

Source Code

public static int getNumberOfCategories() {
return Categories.values().length;
}

Called Methods

  • jfreerails.world.cargo.CargoType.Categories.values (external)

hashCode

Class: jfreerails.world.accounts.TransactionAndTimeStamp

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = t.hashCode();
result = 29 * result + timeStamp.hashCode();
return result;
}

paintRect

Class: jfreerails.client.renderer.TerrainLayer

Documentation

No documentation available

Source Code

public void paintRect(Graphics g, Rectangle visibleRect) {
throw new UnsupportedOperationException(
"Method not yet implemented.");
}

Called Methods

No outgoing method calls

getMessage

Class: jfreerails.network.specifics.LogOnResponse

Documentation

No documentation available

Source Code

public String getMessage() {
return message;
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.world.train.ConstAcc

Documentation

No documentation available

Source Code

@Override
public String toString() {
String str = "ConstAcc [a=" + a + ", u=" + u + ", dt=" + finalT + "]";
return str;
}

Called Methods

No outgoing method calls

getWorld

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

private World getWorld() {
return serverGameModel.getWorld();
}

BuildTrackStrategy

Class: jfreerails.controller.BuildTrackStrategy

Documentation

/** Creates a new instance of BuildTrackStrategy */

Source Code

/** Creates a new instance of BuildTrackStrategy */
private BuildTrackStrategy(int[] r) {
rules = r;
}

Called Methods

No outgoing method calls

occupiedTrackSections

Class: jfreerails.controller.MoveTrainPreMove

Documentation

No documentation available

Source Code

private HashMap<TrackSection, Integer> occupiedTrackSections(ReadOnlyWorld w) {
HashMap<TrackSection, Integer> occupiedTrackSections = new HashMap<TrackSection, Integer>();
for (int i = 0; i < w.size(principal, KEY.TRAINS); i++) {
TrainModel train = (TrainModel) w.get(principal,
KEY.TRAINS, i);
if (null == train)
continue;
TrainAccessor ta = new TrainAccessor(w, principal, i);
GameTime gt = w.currentTime();
if(ta.isMoving(gt.getTicks())){
HashSet<TrackSection> sections = ta.occupiedTrackSection(gt.getTicks());
for (TrackSection section : sections) {
if(occupiedTrackSections.containsKey(section)){
int count = occupiedTrackSections.get(section);
count++;
occupiedTrackSections.put(section, count);
}else{
occupiedTrackSections.put(section, 1);
}
}
}
}
return occupiedTrackSections;
}

getBefore

Class: jfreerails.move.RemoveItemFromListMove

Documentation

No documentation available

Source Code

public FreerailsSerializable getBefore() {
return item;
}

Called Methods

No outgoing method calls

calcT

Class: jfreerails.world.train.CompositeSpeedAgainstTime

Documentation

No documentation available

Source Code

public double calcT(double s) {
if(s == this.finalS) return this.finalT;
if (s > finalS)
throw new IllegalArgumentException(String.valueOf(s));
double sSoFar = 0;
double tSoFar = 0;
int i = 0;
SpeedAgainstTime acc = values.get(i);
while ((sSoFar + acc.getS()) < s) {
sSoFar += acc.getS();
tSoFar += acc.getT();
i++;
acc = values.get(i);
}
double sOffset = s - sSoFar;
if(sOffset >= acc.getS()){
tSoFar += acc.getT();
}else{
tSoFar += acc.calcT(sOffset);
}
return tSoFar;
}

setImage

Class: jfreerails.client.common.ImageManagerImpl

Documentation

No documentation available

Source Code

public void setImage(String relativeFilename, Image i) {
relativeFilename = relativeFilename.replace(' ', '_');
if (i == null) {
throw new NullPointerException(relativeFilename);
}
imageHashMap.put(relativeFilename, i);
}

Called Methods

No outgoing method calls

newmapsJListValueChanged

Class: jfreerails.launcher.SelectMapJPanel

Documentation

No documentation available

Source Code

private void newmapsJListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_newmapsJListValueChanged
if(newmapsJList.getSelectedIndex() != -1)
savedmapsJList.clearSelection();
validateInput();
}//GEN-LAST:event_newmapsJListValueChanged

ImmutableCargoBundle

Class: jfreerails.world.cargo.ImmutableCargoBundle

Documentation

No documentation available

Source Code

private ImmutableCargoBundle() {
batches = new ImList<CargoBatch>();
amounts = new ImInts();
}

Called Methods

No outgoing method calls

findstep

Class: jfreerails.controller.SimpleAStarPathFinder

Documentation

No documentation available

Source Code

public int findstep(int currentPosition, int[] targets,
GraphExplorer tempExplorer) {
try {
return findpath(new int[] { currentPosition }, targets,
tempExplorer).get(0);
} catch (PathNotFoundException e) {
return PATH_NOT_FOUND;
}
}

writeToClient

Class: jfreerails.network.InetConnection2Client

Documentation

No documentation available

Source Code

public void writeToClient(FreerailsSerializable object) throws IOException {
send(object);
}

getAll

Class: jfreerails.util.LRUCache

Documentation

/**
* Returns a <code>Collection</code> that contains a copy of all cache
* entries.
*
* @return a <code>Collection</code> with a copy of the cache content.
*/

Source Code

/**
* Returns a <code>Collection</code> that contains a copy of all cache
* entries.
*
* @return a <code>Collection</code> with a copy of the cache content.
*/
public synchronized Collection<Map.Entry<K, V>> getAll() {
return new ArrayList<Map.Entry<K, V>>(map.entrySet());
}

Called Methods

No outgoing method calls

isDouble

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

public boolean isDouble() {
return false;
}

Called Methods

No outgoing method calls

fullScreenButtonStateChanged

Class: jfreerails.launcher.ClientOptionsJPanel

Documentation

No documentation available

Source Code

private void fullScreenButtonStateChanged(javax.swing.event.ChangeEvent evt) {// GEN-FIRST:event_fullScreenButtonStateChanged
jList1.setEnabled(fullScreenButton.isSelected());
validateInput();
}// GEN-LAST:event_fullScreenButtonStateChanged

duration

Class: jfreerails.world.train.TrainMotion

Documentation

No documentation available

Source Code

public double duration() {
return duration;
}

Called Methods

No outgoing method calls

sendMessage

Class: jfreerails.network.EchoGameServer

Documentation

No documentation available

Source Code

synchronized void sendMessage(FreerailsSerializable m) {
/* Send messages. */
for (int i = 0; i < connections.size(); i++) {
Connection2Client connection = connections.get(i);
try {
connection.writeToClient(m);
connection.flush();
logger.fine("Sent ok: " + m);
} catch (IOException e) {
try {
if (connection.isOpen()) {
connection.disconnect();
}
} catch (IOException e1) {
// hope this doesn't happen.
e1.printStackTrace();
}
}
}
}

getAmount

Class: jfreerails.world.cargo.MutableCargoBundle

Documentation

No documentation available

Source Code

public int getAmount(int cargoType) {
Iterator<CargoBatch> it = cargoBatchIterator();
int amount = 0;
while (it.hasNext()) {
CargoBatch cb = it.next();
if (cb.getCargoType() == cargoType) {
amount += getAmount(cb);
}
}
return amount;
}

NullTrackPieceRenderer

Class: jfreerails.client.renderer.NullTrackPieceRenderer

Documentation

No documentation available

Source Code

private NullTrackPieceRenderer() {
}

Called Methods

No outgoing method calls

isDifferent

Class: jfreerails.world.top.WorldDiffs

Documentation

No documentation available

Source Code

public boolean isDifferent(){
return (mapDiff.size() != 0) || (listDiff.size() != 0);
}

Called Methods

No outgoing method calls

renderOffScreenImage

Class: jfreerails.client.renderer.ZoomedOutMapRenderer

Documentation

No documentation available

Source Code

private void renderOffScreenImage() {
if (isDirty) {
Graphics2D mapGraphics = mapImage.createGraphics();
mapGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
mapGraphics.setClip(0, 0, imageWidth, imageHeight);
mapGraphics.clearRect(0, 0, imageWidth, imageHeight);
mapGraphics.drawImage(one2oneImage, affineTransform, null);
isDirty = false;
}
}

Called Methods

No outgoing method calls

getLocation

Class: jfreerails.world.station.StationModel

Documentation

No documentation available

Source Code

public ImPoint getLocation(){
return new ImPoint(x, y);
}

Called Methods

No outgoing method calls

subPath

Class: jfreerails.world.train.PathOnTiles

Documentation

/**
* Returns a FreerailsPathIterator that exposes a sub section of the path
* this object represents.
*
* @throws IllegalArgumentException
* if offset < 0
* @throws IllegalArgumentException
* if length <= 0
* @throws IllegalArgumentException
* if offset + length > getLength()
*
*/

Source Code

/**
* Returns a FreerailsPathIterator that exposes a sub section of the path
* this object represents.
*
* @throws IllegalArgumentException
* if offset < 0
* @throws IllegalArgumentException
* if length <= 0
* @throws IllegalArgumentException
* if offset + length > getLength()
*
*/
public FreerailsPathIterator subPath(double offset, double length) {
if (offset < 0)
throw new IllegalArgumentException();
if (length <= 0)
throw new IllegalArgumentException();
if ((offset + length) > getTotalDistance())
throw new IllegalArgumentException(offset +" + "+ length+" > " +getTotalDistance());
final LinkedList<ImPoint> points = new LinkedList<ImPoint>();
ImPoint tile = getStart();
int tileX = tile.x;
int tileY = tile.y;
int distanceSoFar = 0;
for (int i = 0; i < vectors.size(); i++) {
if (distanceSoFar > offset + length) {
break;
}
if (distanceSoFar >= offset) {
int x = TILE_DIAMETER / 2 + TILE_DIAMETER * tileX;
int y = TILE_DIAMETER / 2 + TILE_DIAMETER * tileY;
points.add(new ImPoint(x, y));
}
Step v = vectors.get(i);
tileX += v.deltaX;
tileY += v.deltaY;
distanceSoFar += v.getLength();
}
ImPoint first = getPoint(offset);
if (points.size() == 0) {
points.addFirst(first);
} else if (!points.getFirst().equals(first)) {
points.addFirst(first);
}
ImPoint last = getPoint(offset + length);
if (!points.getLast().equals(last)) {
points.addLast(last);
}
return new FreerailsPathIterator() {
private static final long serialVersionUID = 1L;
int index = 0;
public boolean hasNext() {
return (index + 1) < points.size();
}
public void nextSegment(IntLine line) {
if (!hasNext()) {
throw new NoSuchElementException();
}
ImPoint a = points.get(index);
line.x1 = a.x;
line.y1 = a.y;
ImPoint b = points.get(index + 1);
line.x2 = b.x;
line.y2 = b.y;
index++;
}
};
}

StationTypesPopup

Class: jfreerails.client.top.StationTypesPopup

Documentation

No documentation available

Source Code

public StationTypesPopup() {
}

Called Methods

No outgoing method calls

start_Cargo_Types

Class: jfreerails.server.parser.CargoAndTerrainHandler

Documentation

/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/

Source Code

/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/
public void start_Cargo_Types(final Attributes meta) throws SAXException;

Called Methods

No outgoing method calls

nextSegment

Class: jfreerails.controller.ToAndFroPathIterator

Documentation

No documentation available

Source Code

public void nextSegment(IntLine line) {
if (this.hasNext()) {
if (!path.hasNext()) {
forwards = !forwards;
path = new FreerailsPathIteratorImpl(list, forwards);
}
path.nextSegment(line);
} else {
throw new NoSuchElementException();
}
}

stepForward

Class: jfreerails.world.train.PathWalkerImpl

Documentation

/**
* Specify the distance this PathWalker is to progress along the current
* step.
*/

Source Code

/**
* Specify the distance this PathWalker is to progress along the current
* step.
*/
public void stepForward(double distance) {
distanceOfThisStepRemaining += distance;
}

Called Methods

No outgoing method calls

setupMap

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public void setupMap(int mapWidth, int mapHeight) {
map = new FreerailsSerializable[mapWidth][mapHeight];
for (int x = 0; x < mapWidth; x++) {
for (int y = 0; y < mapHeight; y++) {
map[x][y] = FreerailsTile.NULL;
}
}
}

Called Methods

No outgoing method calls

setUp

Class: jfreerails.util.ListXDDiffsTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
super.setUp();
map = new TreeMap<ListKey, Object>();
list1d = new List1DDiff<Object>(map, list1d, listid.list1);
list2d = new List2DDiff<Object>(map, list2d, listid.list2);
list3d = new List3DDiff<Object>(map, list3d, listid.list3);
}

read

Class: jfreerails.network.specifics.FreerailsClient

Documentation

No documentation available

Source Code

final FreerailsSerializable read() {
try {
return this.connection2Server.waitForObjectFromServer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
throw new IllegalStateException();
}

CompressedInputStream

Class: jfreerails.util.CompressedInputStream

Documentation

No documentation available

Source Code

public CompressedInputStream(InputStream in) {
super(in);
buffer = new byte[0x7d000];
compBuffer = new byte[(int) (buffer.length * 1.2D)];
readIndex = 0;
maxReadIndex = 0;
inflater = new Inflater();
}

Called Methods

No outgoing method calls

sizeD2

Class: jfreerails.util.List2DImpl

Documentation

No documentation available

Source Code

public int sizeD2(int d1) {
return elementData.get(d1).size();
}

Called Methods

No outgoing method calls

getLength

Class: jfreerails.world.common.IntLine

Documentation

/**
* @return the length of the line
*/

Source Code

/**
* @return the length of the line
*/
public double getLength() {
int sumOfSquares = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
if(sumOfSquares < MAX_SQUAREROOTS) {
return squareRoots[sumOfSquares];
}
return Math.sqrt(sumOfSquares);
}

Called Methods

No outgoing method calls

execute

Class: jfreerails.network.specifics.SetWorldMessage2Client

Documentation

No documentation available

Source Code

public MessageStatus execute(ClientControlInterface client) {
client.setGameModel(world.defensiveCopy());
return new MessageStatus(id, true);
}

ignorableWhitespace

Class: jfreerails.server.parser.CargoAndTerrainParser

Documentation

/**
* This SAX interface method is implemented by the parser.
*
*/

Source Code

/**
* This SAX interface method is implemented by the parser.
*
*/
public final void ignorableWhitespace(char[] chars, int start, int len)
throws SAXException {
}

Called Methods

No outgoing method calls

getStep

Class: jfreerails.world.train.PathOnTiles

Documentation

No documentation available

Source Code

public Step getStep(int i) {
return vectors.get(i);
}

FlatTrackExplorerTest

Class: jfreerails.controller.FlatTrackExplorerTest

Documentation

No documentation available

Source Code

public FlatTrackExplorerTest(String arg0) {
super(arg0);
}

Called Methods

No outgoing method calls

shutdownOutput

Class: jfreerails.network.InetConnection

Documentation

No documentation available

Source Code

synchronized void shutdownOutput() throws IOException {
socket.shutdownOutput();
if (socket.isInputShutdown() && socket.isOutputShutdown()) {
socket.close();
}
}

Called Methods

No outgoing method calls

isInUse

Class: jfreerails.controller.ScreenHandler

Documentation

No documentation available

Source Code

public synchronized boolean isInUse() {
return isInUse;
}

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.view.ConfirmExitJPanel

Documentation

No documentation available

Source Code

public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
closeJButton.setAction(closeAction);
}

Called Methods

No outgoing method calls

testCargoType

Class: jfreerails.world.cargo.CargoTypeTest

Documentation

No documentation available

Source Code

public void testCargoType() {
// Test that invalid categories get rejected.
try {
new CargoType(10, "Test", Categories
.getCategory("Non valid category"));
fail();
} catch (Exception e) {
}
try {
new CargoType(10, "Test", Categories.Mail);
} catch (Exception e) {
fail();
}
}

Called Methods

  • jfreerails.world.cargo.CargoType.Categories.getCategory (external)

removeLastWagon

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void removeLastWagon() {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
ImInts oldConsist = oldOrders.consist;
if( null == oldConsist){
//consist can be null if there is no
//scheduled change of wagons.
//Fixes freerails bug 1687677 and freerails2 bug 2014234
return;
}
int newLength = oldConsist.size() - 1;
if (newLength < 0) {
//No wagons to remove!
return;
}
ImInts newConsist = oldConsist.removeLast();
newOrders = new TrainOrdersModel(oldOrders.getStationID(), newConsist,
oldOrders.waitUntilFull, false);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}

tryMove

Class: jfreerails.move.ChangeProductionAtEngineShopMove

Documentation

No documentation available

Source Code

private MoveStatus tryMove(World w, ImList<PlannedTrain> stateA) {
// Check that the specified station exists.
if (!w.boundsContain(principal, KEY.STATIONS, this.stationNumber)) {
return MoveStatus.moveFailed(this.stationNumber + " " + principal);
}
StationModel station = (StationModel) w.get(principal, KEY.STATIONS,
stationNumber);
if (null == station) {
return MoveStatus.moveFailed(this.stationNumber + " " + principal
+ " is does null");
}
// Check that the station is building what we expect.
if (null == station.getProduction()) {
if (null == stateA) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed(this.stationNumber + " " + principal);
}
if (station.getProduction().equals(stateA)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed(this.stationNumber + " " + principal);
}

getCheapest

Class: jfreerails.controller.BuildTrackStrategy

Documentation

No documentation available

Source Code

private static Integer getCheapest(TrackRule.TrackCategories category,
ReadOnlyWorld w) {
TrackRule cheapest = null;
Integer cheapestID = null;
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule rule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
if (rule.getCategory().equals(category)) {
if (null == cheapest
|| cheapest.getPrice().getAmount() > rule.getPrice()
.getAmount()) {
cheapest = rule;
cheapestID = new Integer(i);
}
}
}
return cheapestID;
}

markSupported

Class: jfreerails.util.CompressedInputStream

Documentation

No documentation available

Source Code

@Override
public boolean markSupported() {
return false;
}

Called Methods

No outgoing method calls

getOrderToGoto

Class: jfreerails.world.train.Schedule

Documentation

/** Returns the number of the order the train is currently carry out. */

Source Code

/** Returns the number of the order the train is currently carry out. */
int getOrderToGoto();

Called Methods

No outgoing method calls

tryDoMove

Class: jfreerails.move.ChangeProductionAtEngineShopMove

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
return tryMove(w, before);
}

LegalTrackConfigurationsTest

Class: jfreerails.world.track.LegalTrackConfigurationsTest

Documentation

No documentation available

Source Code

public LegalTrackConfigurationsTest(java.lang.String testName) {
super(testName);
}

Called Methods

No outgoing method calls

testLogon

Class: jfreerails.network.specifics.FreerailsClientTest

Documentation

No documentation available

Source Code

public void testLogon() {
try {
/* Test 1 : connecting a client. */
assertEquals("No client connected yet.", 0, server
.countOpenConnections());
FreerailsClient client = new FreerailsClient();
LogOnResponse response = client.connect(getIpAddress(), getPort(),
"name", "password");
assertTrue(response.isSuccessful());
assertEquals(1, server.countOpenConnections());
assertMapsAndSaveGamesReceived(client);
assertConnectClientsEquals(client, new ImStringList("name"));
/* Test 2 : a client that has already logged on. */
FreerailsClient client2 = new FreerailsClient();
response = client2.connect(getIpAddress(), getPort(), "name",
"password");
assertFalse("The player is already logged on.", response
.isSuccessful());
assertEquals(1, server.countOpenConnections());
/* Test 3 : connecting a client. */
FreerailsClient client3 = new FreerailsClient();
response = client3.connect(getIpAddress(), getPort(), "name3",
"password");
assertTrue(response.isSuccessful());
assertEquals(2, server.countOpenConnections());
/* read list of connected clients. */
assertConnectClientsEquals(client,
new ImStringList("name", "name3"));
assertMapsAndSaveGamesReceived(client3);
assertConnectClientsEquals(client3, new ImStringList("name",
"name3"));
/* Test 4 : disconnect the client from test 1. */
client.disconnect();
assertEquals(1, server.countOpenConnections());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}

getTrackConfiguration

Class: jfreerails.world.track.NullTrackPiece

Documentation

No documentation available

Source Code

public TrackConfiguration getTrackConfiguration() {
return TrackConfiguration.from9bitTemplate(0);
}

ArrayBase

Class: jfreerails.util.ArrayBase

Documentation

/**
* Constructor with partial specification.
*
* @param size
* number of elements initially allowed in array
* @param type
* array element type
*/

Source Code

/**
* Constructor with partial specification.
*
* @param size
* number of elements initially allowed in array
* @param type
* array element type
*/
public ArrayBase(int size, Class type) {
this(size, Integer.MAX_VALUE, type);
}

showTrainOrders

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showTrainOrders() {
WorldIterator wi = new NonNullElements(KEY.TRAINS, world, modelRoot
.getPrincipal());
if (!wi.next()) {
modelRoot.setProperty(Property.QUICK_MESSAGE, "Cannot"
+ " show train orders since there are no" + " trains!");
} else {
trainDialogueJPanel.display(wi.getIndex());
this.showContent(trainDialogueJPanel);
}
}

end_Cargo_Types

Class: jfreerails.server.parser.CargoAndTerrainHandler

Documentation

/**
* A container element end event handling method.
*
*/

Source Code

/**
* A container element end event handling method.
*
*/
public void end_Cargo_Types() throws SAXException;

Called Methods

No outgoing method calls

execute

Class: jfreerails.network.specifics.RefreshListOfGamesMessage2Server

Documentation

No documentation available

Source Code

public MessageStatus execute(ServerControlInterface server) {
server.refreshSavedGames();
return new MessageStatus(id, true);
}

removeLastD1

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

public void removeLastD1() {
super.removeLastList();
}

isOpen

Class: jfreerails.network.SynchronizedFlag

Documentation

No documentation available

Source Code

public synchronized boolean isOpen() {
return isOpen;
}

Called Methods

No outgoing method calls

initComponents

Class: jfreerails.client.view.LoadGameJPanel

Documentation

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/

Source Code

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jLabel1 = new javax.swing.JLabel();
okButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
refreshButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jScrollPane1.setViewportView(jList1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(jScrollPane1, gridBagConstraints);
jLabel1.setText("Please select a game to load.");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(jLabel1, gridBagConstraints);
okButton.setText("OK");
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(okButton, gridBagConstraints);
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(cancelButton, gridBagConstraints);
refreshButton.setText("Refresh");
refreshButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
refreshButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(refreshButton, gridBagConstraints);
}// </editor-fold>//GEN-END:initComponents

showStationInfoActionPerformed

Class: experimental.DialogueBoxTester

Documentation

No documentation available

Source Code

private void showStationInfoActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showStationInfoActionPerformed
// Add your handling code here:
int stationNumber = 0;
dialogueBoxController.showStationInfo(stationNumber);
}// GEN-LAST:event_showStationInfoActionPerformed

getNumberOfKeys

Class: jfreerails.world.top.ITEM

Documentation

No documentation available

Source Code

static int getNumberOfKeys() {
return ITEM.class.getFields().length;
}

Called Methods

No outgoing method calls

removeLast

Class: jfreerails.world.top.World

Documentation

/**
* Removes the last element from the specified list.
*/

Source Code

/**
* Removes the last element from the specified list.
*/
FreerailsSerializable removeLast(FreerailsPrincipal principal, KEY key);

Called Methods

No outgoing method calls

waitForObjectFromClient

Class: jfreerails.network.LocalConnection

Documentation

No documentation available

Source Code

public FreerailsSerializable waitForObjectFromClient() throws IOException,
InterruptedException {
synchronized (fromClient) {
if (fromClient.size() == 0) {
fromClient.wait();
}
if (status.isOpen()) {
return fromClient.getFirst();
}
throw new IOException();
}
}

currentTime

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public GameTime currentTime() {
return time;
}

Called Methods

No outgoing method calls

formComponentShown

Class: jfreerails.client.view.SelectStationJPanel

Documentation

No documentation available

Source Code

private void formComponentShown(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_formComponentShown
setZoom();
}// GEN-LAST:event_formComponentShown

disconnect

Class: jfreerails.network.Connection2Client

Documentation

/**
* Disconnect from the client. When this method returns, calling isOpen() on
* this object returns false <b>and</b> calling isOpen() on the
* corresponding Connection2Server held by the client also returns false.
*
* @throws IOException
*/

Source Code

/**
* Disconnect from the client. When this method returns, calling isOpen() on
* this object returns false <b>and</b> calling isOpen() on the
* corresponding Connection2Server held by the client also returns false.
*
* @throws IOException
*/
void disconnect() throws IOException;

Called Methods

No outgoing method calls

InetConnection2Server

Class: jfreerails.network.InetConnection2Server

Documentation

No documentation available

Source Code

public InetConnection2Server(String ip, int port) throws IOException {
super(ip, port);
serverDetails = "server at " + ip + ":" + port;
}

buildTrack

Class: jfreerails.server.MapCustomizer

Documentation

No documentation available

Source Code

public MapCustomizer buildTrack(ImPoint a, ImPoint b) throws PathNotFoundException {
pathFinder.setupSearch(a, b, bts);
pathFinder.search(-1);
List<ImPoint> pathAsPoints = pathFinder.pathAsPoints();
ImPoint from = a;
for (int i = 0; i < pathAsPoints.size(); i++) {
ImPoint to = pathAsPoints.get(i);
Step vector = Step.getInstance(to.x - from.x, to.y
- from.y);
FreerailsTile tile = (FreerailsTile) w.getTile(
from.x, from.y);
if (!tile.getTrackPiece().getTrackConfiguration().contains(vector)) {
producer.buildTrack(from, vector);
}
from = to;
}
return this;
}

ignoreTestAutoConsist

Class: jfreerails.controller.MoveTrainPreMove2ndTest

Documentation

/** Tests that a train with 'select wagons automatically' enable behaves correctly.*/

Source Code

/** Tests that a train with 'select wagons automatically' enable behaves correctly.*/
public void ignoreTestAutoConsist(){
TrainAccessor ta = new TrainAccessor(world, principal, 0);
//Remove all wagons from the train.
TrainModel model = ta.getTrain();
model = model.getNewInstance(model.getEngineType(), new ImInts());
world.set(principal, KEY.TRAINS, 0, model);
//Change trains schedule to auto consist.
TrainOrdersModel order0 = new TrainOrdersModel(1, null, false, true);
TrainOrdersModel order1 = new TrainOrdersModel(2, null, false, true);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
world.set(principal, KEY.TRAIN_SCHEDULES, 0, s.toImmutableSchedule());
assertEquals(0, ta.getSchedule().getOrderToGoto());
//Add 35 unit of cargo #0 to station 1.
StationModel station0 = (StationModel)world.get(principal, KEY.STATIONS, 1);
int cargoBundleId = station0.getCargoBundleID();
MutableCargoBundle mcb = new MutableCargoBundle();
final int AMOUNT_OF_CARGO = 35;
mcb.addCargo(new CargoBatch(0, 0,0, 0, 0), AMOUNT_OF_CARGO);
world.set(principal, KEY.CARGO_BUNDLES, cargoBundleId, mcb.toImmutableCargoBundle());
//Make station2 demand cargo #0;
boolean[] boolArray = new boolean[world.size(SKEY.CARGO_TYPES)];
boolArray[0] = true;
Demand4Cargo demand = new Demand4Cargo(boolArray);
StationModel station2 = (StationModel)world.get(principal, KEY.STATIONS, 2);
StationModel stationWithNewDemand = new StationModel(station2, demand);
world.set(principal, KEY.STATIONS, 2, stationWithNewDemand);
//The train should be bound for station 1.
assertEquals(1, ta.getSchedule().getStationToGoto());
//Make train call at station 1.
PositionOnTrack pot;
TrainMotion tm;
do {
tm = moveTrain();
pot = tm.getFinalPosition();
} while (pot.getX() < station1Location.x);
assertEquals(station1Location.x, pot.getX());
assertEquals(station1Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
tm = moveTrain();
pot = tm.getFinalPosition();
//The train should be bound for station 2.
assertEquals(2, ta.getSchedule().getStationToGoto());
//Check that the train has picked up the cargo.
//The train should have one wagon of type #0
assertEquals(new ImInts(0), ta.getTrain().getConsist());
assertEquals(AMOUNT_OF_CARGO, ta.getCargoBundle().getAmount(0));
}

getWagonImages

Class: jfreerails.client.top.RenderersRootImpl

Documentation

No documentation available

Source Code

public TrainImages getWagonImages(int type) {
return wagonImages.get(type);
}

Called Methods

No outgoing method calls

getTileViewWithRGBValue

Class: jfreerails.client.top.QuickRGBTileRendererList

Documentation

No documentation available

Source Code

public TileRenderer getTileViewWithRGBValue(int rgb) {
Integer i = rgb2index.get(new Integer(rgb));
this.simpleTileRenderer.setImage(images[i.intValue()]);
return simpleTileRenderer;
}

Called Methods

  • jfreerails.client.top.QuickRGBTileRendererList.SimpleTileRenderer.setImage (external)

MapBackgroundRender

Class: jfreerails.client.renderer.MapBackgroundRender

Documentation

No documentation available

Source Code

public MapBackgroundRender(ReadOnlyWorld w, RenderersRoot rr,
ModelRoot modelRoot) {
trackLayer = new TrackLayer(w, rr);
terrainLayer = new TerrainLayer(w, rr);
mapSize = new Dimension(w.getMapWidth(), w.getMapHeight());
cityNames = new CityNamesRenderer(w);
stationNames = new StationNamesRenderer(w, modelRoot);
}

addTerrainTileTypesList

Class: jfreerails.server.TileSetFactoryImpl

Documentation

No documentation available

Source Code

public void addTerrainTileTypesList(World w) {
try {
java.net.URL url = RunTypesParser.class
.getResource("/jfreerails/data/cargo_and_terrain.xml");
CargoAndTerrainParser.parse(url, new CargoAndTerrainHandlerImpl(w));
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException();
}
}

GUIComponentFactoryImpl

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

public GUIComponentFactoryImpl(ModelRootImpl mr, ActionRoot ar) {
modelRoot = mr;
actionRoot = ar;
userInputOnMapController = new UserInputOnMapController(modelRoot, ar);
buildMenu = new jfreerails.client.top.BuildMenu();
mapViewJComponent = new MapViewJComponentConcrete();
mainMapScrollPane1 = new JScrollPane();
overviewMapContainer = new OverviewMapJComponent(r);
stationTypesPopup = new StationTypesPopup();
MainMapAndOverviewMapMediator mediator = new MainMapAndOverviewMapMediator();
mediator.setup(overviewMapContainer, mainMapScrollPane1.getViewport(),
mapViewJComponent, r);
trainsJTabPane = new RHSJTabPane();
datejLabel = new DateJLabel();
cashjLabel = new CashJLabel();
clientJFrame = new ClientJFrame(this);
dialogueBoxController = new DialogueBoxController(clientJFrame,
modelRoot);
actionRoot.setDialogueBoxController(dialogueBoxController);
modelRoot.addSplitMoveReceiver(new MoveReceiver() {
public void processMove(Move move) {
if (move instanceof ChangeGameSpeedMove) {
ChangeGameSpeedMove speedMove = (ChangeGameSpeedMove) move;
for (Enumeration<Action> actionsEnum = speedActions
.getActions(); actionsEnum.hasMoreElements();) {
Action action = actionsEnum.nextElement();
String actionName = (String) action
.getValue(Action.NAME);
if (actionName.equals(actionRoot.getServerControls()
.getGameSpeedDesc(speedMove.getNewSpeed()))) {
speedActions.setSelectedItem(actionName);
}
break;
}
}
}
});
userMessageGenerator = new UserMessageGenerator(this.modelRoot,
this.actionRoot);
modelRoot.addCompleteMoveReceiver(userMessageGenerator);
}

getOrderToGoto

Class: jfreerails.world.train.ImmutableSchedule

Documentation

No documentation available

Source Code

public int getOrderToGoto() {
return hasPriorityOrders ? 0 : nextScheduledOrder;
}

Called Methods

No outgoing method calls

testMove2

Class: jfreerails.controller.AddTrainPreMoveTest

Documentation

No documentation available

Source Code

public void testMove2() {
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0),
stationA, principal, defaultSchedule);
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.ok);
ActivityIterator ai = world.getActivities(principal, 0);
TrainMotion tm = (TrainMotion) ai.getActivity();
assertEquals(0d, tm.duration());
assertEquals(0d, tm.getSpeedAtEnd());
assertEquals(0d, tm.getDistance(0));
PositionOnTrack pot = tm.getFinalPosition();
assertNotNull(pot);
assertEquals(EAST, pot.facing());
assertEquals(13, pot.getX());
assertEquals(10, pot.getY());
}

hashCode

Class: jfreerails.world.common.ImPoint

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return x * 1000 + y;
}

Called Methods

No outgoing method calls

solveQuadratic

Class: jfreerails.util.Utils

Documentation

/**
* Returns the largest solution of the quadratic equation ax<sup><font
* size="-1">2</font></sup> + bx + c = 0.
*
* @throws IllegalArgumentException
* if <code>a == 0</code>
* @throws IllegalArgumentException
* if <code>(b * b - 4 * a * c) < 0</code>
*/

Source Code

/**
* Returns the largest solution of the quadratic equation ax<sup><font
* size="-1">2</font></sup> + bx + c = 0.
*
* @throws IllegalArgumentException
* if <code>a == 0</code>
* @throws IllegalArgumentException
* if <code>(b * b - 4 * a * c) < 0</code>
*/
public static double solveQuadratic(double a, double b, double c)
throws IllegalArgumentException {
if (a == 0) {
throw new IllegalArgumentException("a == 0");
}
double disc = b * b - 4 * a * c;
if (disc < 0)
throw new IllegalArgumentException("(b * b - 4 * a * c) < 0");
return (-b + StrictMath.sqrt(disc)) / (2 * a);
}

Called Methods

No outgoing method calls

moveCursorOneTile

Class: jfreerails.client.top.UserInputOnMapController

Documentation

No documentation available

Source Code

private void moveCursorOneTile(Step v) {
setCursorMessage(null);
ImPoint cursorMapPosition = this.getCursorPosition();
ImPoint tryThisPoint = new ImPoint(cursorMapPosition.x + v.getDx(),
cursorMapPosition.y + v.getDy());
/* Move the cursor. */
if (legalRectangleContains(tryThisPoint)) {
setCursorPosition(tryThisPoint);
cursorOneTileMove(cursorMapPosition, v);
} else {
this.setCursorMessage("Illegal cursor position!");
}
}

formComponentResized

Class: jfreerails.client.view.SelectStationJPanel

Documentation

No documentation available

Source Code

private void formComponentResized(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_formComponentResized
setZoom();
}// GEN-LAST:event_formComponentResized

getTrackTypeID

Class: jfreerails.world.track.TrackPieceImpl

Documentation

No documentation available

Source Code

public int getTrackTypeID() {
return ruleNumber;
}

Called Methods

No outgoing method calls

ClientJFrame

Class: jfreerails.client.top.ClientJFrame

Documentation

/** Creates new form ClientJFrame. */

Source Code

/** Creates new form ClientJFrame. */
public ClientJFrame(GUIComponentFactory gcf) {
setup(gcf);
}

TerrainRandomiser

Class: jfreerails.server.TerrainRandomiser

Documentation

No documentation available

Source Code

public TerrainRandomiser(Vector<Integer> num, Vector<Integer> num2) {
terrainTypes = num;
non_terrainTypes = num2;
}

Called Methods

No outgoing method calls

canSetGotoStation

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public boolean canSetGotoStation(int orderNumber) {
return !(orderNumber == 0 && hasPriorityOrders);
}

Called Methods

No outgoing method calls

viewModeActionPerformed

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

No documentation available

Source Code

private void viewModeActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_viewModeActionPerformed
setVisible(false, false, false, false);
cancelStationPlacement();
setTrackBuilderMode(IGNORE_TRACK);
}// GEN-LAST:event_viewModeActionPerformed

testDoMove

Class: jfreerails.move.ChangeTrackPieceMoveTest

Documentation

No documentation available

Source Code

public void testDoMove() {
setUp();
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
TrackConfiguration newConfig;
// Try building the simplest piece of track.
newConfig = TrackConfiguration.getFlatInstance("000010000");
oldTrackPiece = ((FreerailsTile) getWorld().getTile(0, 0)).getTrackPiece();
TrackRule r = (TrackRule) getWorld().get(SKEY.TRACK_RULES, 0);
newTrackPiece = new TrackPieceImpl(newConfig, r, 0, 0);
assertMoveDoMoveIsOk(oldTrackPiece, newTrackPiece);
}

getWagonImages

Class: jfreerails.client.renderer.MyRenderersRoot

Documentation

No documentation available

Source Code

@Override
public TrainImages getWagonImages(int type) {
return this.trainImages;
}

Called Methods

No outgoing method calls

NullTrackType

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

private NullTrackType() {
}

Called Methods

No outgoing method calls

getPrincipal

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public FreerailsPrincipal getPrincipal() {
if (null == playerPrincipal) {
throw new NullPointerException();
}
return playerPrincipal;
}

Called Methods

No outgoing method calls

getT

Class: jfreerails.world.train.SpeedAgainstTime

Documentation

/**
* @return The time taken to travel the distance given by getS().
*/

Source Code

/**
* @return The time taken to travel the distance given by getS().
*/
double getT();

Called Methods

No outgoing method calls

getTrainLength

Class: jfreerails.world.train.TrainMotion

Documentation

No documentation available

Source Code

public int getTrainLength() {
return trainLength;
}

Called Methods

No outgoing method calls

generateFilename

Class: jfreerails.client.renderer.StandardTileRenderer

Documentation

No documentation available

Source Code

private String generateFilename() {
return generateFilename(this.getTerrainType());
}

sizeD2

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

public int sizeD2(int d1) {
return super.size(d1);
}

getLength

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public int getLength() {
return xpoints.size();
}

getScaledImage

Class: jfreerails.client.common.ImageManagerImpl

Documentation

/**
* Returns the specified image scaled so that its height is equal to the
* specified height.
*/

Source Code

/**
* Returns the specified image scaled so that its height is equal to the
* specified height.
*/
public Image getScaledImage(String relativeFilename, int height)
throws IOException {
relativeFilename = relativeFilename.replace(' ', '_');
if (!isValid(relativeFilename))
throw new IllegalArgumentException(relativeFilename
+ " must match " + A_REGEX);
String hashKey = relativeFilename + height;
if (this.scaledImagesHashMap.containsKey(hashKey)) {
return scaledImagesHashMap.get(hashKey);
}
Image i = getImage(relativeFilename);
if (i.getHeight(null) == height) {
return i;
}
int width = (i.getWidth(null) * height) / i.getHeight(null);
Image compatibleImage = newBlankImage(height, width);
Graphics2D g = (Graphics2D) compatibleImage.getGraphics();
g.setRenderingHints(this.renderingHints);
g.drawImage(i, 0, 0, width, height, null);
scaledImagesHashMap.put(hashKey, compatibleImage);
return compatibleImage;
}

main

Class: jfreerails.client.common.SoundManager

Documentation

No documentation available

Source Code

public static void main(String[] args) {
SoundManager soundPlayer = getSoundManager();
for (int i = 0; i < 100; i++) {
soundPlayer.playSound("/jfreerails/client/sounds/cash.wav", 10);
try {
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

getTransaction

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

No documentation available

Source Code

Transaction getTransaction(FreerailsPrincipal p, int i);

Called Methods

No outgoing method calls

nextInt

Class: jfreerails.util.FreerailsIntIterator

Documentation

No documentation available

Source Code

int nextInt();

Called Methods

No outgoing method calls

testMap

Class: jfreerails.world.top.WorldDiffsTest

Documentation

No documentation available

Source Code

public void testMap() {
WorldImpl underlyingWorld = new WorldImpl(21, 8);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(21, worldDiff.getMapWidth());
assertEquals(8, worldDiff.getMapHeight());
FreerailsTile tile = (FreerailsTile) underlyingWorld.getTile(2, 2);
assertNotNull(tile);
assertEquals(tile, worldDiff.getTile(2, 2));
FreerailsTile newTile = FreerailsTile.getInstance(999);
worldDiff.setTile(3, 5, newTile);
assertEquals(newTile, worldDiff.getTile(3, 5));
Iterator<ImPoint> it = worldDiff.getMapDiffs();
assertEquals(new ImPoint(3, 5), it.next());
}

gotoNextStation

Class: jfreerails.world.train.MutableSchedule

Documentation

/**
* If there are no priority orders, sets the station to goto to the next
* station in the list of orders or if there are no more stations, the first
* station in the list. If priority orders are set, the priority orders
* orders are removed from the schedule and the goto station is not changed.
*/

Source Code

/**
* If there are no priority orders, sets the station to goto to the next
* station in the list of orders or if there are no more stations, the first
* station in the list. If priority orders are set, the priority orders
* orders are removed from the schedule and the goto station is not changed.
*/
public void gotoNextStation() {
if (hasPriorityOrders) {
if (nextScheduledOrder != PRIORITY_ORDERS) {
removeOrder(PRIORITY_ORDERS);
return;
}
}
nextScheduledOrder++;
if (orders.size() <= nextScheduledOrder) {
nextScheduledOrder = 0;
}
}

main

Class: jfreerails.controller.UnexpectedExceptionForm

Documentation

/**
* @param args the command line arguments
*/

Source Code

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
UnexpectedExceptionForm unexpectedExceptionForm = new UnexpectedExceptionForm();
Exception e = new Exception("Oh No..");
String str = ReportBugTextGenerator.genText(e);
unexpectedExceptionForm.setText(str);
unexpectedExceptionForm.setVisible(true);
e.printStackTrace();
}
});
}

sendCommand

Class: jfreerails.controller.ModelRoot

Documentation

No documentation available

Source Code

void sendCommand(Message2Server c);

Called Methods

No outgoing method calls

doMove

Class: jfreerails.move.ChangeTrackPieceMove

Documentation

No documentation available

Source Code

public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus moveStatus = tryDoMove(w, p);
if (!moveStatus.isOk()) {
return moveStatus;
}
move(w, this.trackPieceBefore, this.trackPieceAfter);
return moveStatus;
}

waitForObjectFromClient

Class: jfreerails.network.Connection2Client

Documentation

/**
* Returns the next object read from the client, blocking if non is
* available.
*/

Source Code

/**
* Returns the next object read from the client, blocking if non is
* available.
*/
FreerailsSerializable waitForObjectFromClient() throws IOException,
InterruptedException;

Called Methods

No outgoing method calls

getAmount

Class: jfreerails.world.cargo.ImmutableCargoBundle

Documentation

No documentation available

Source Code

public int getAmount(int cargoType) {
int amount = 0;
for (int i = 0; i < batches.size(); i++) {
if (batches.get(i).getCargoType() == cargoType) {
amount += amounts.get(i);
}
}
return amount;
}

DistanceComparator

Class: experimental.DistanceComparator

Documentation

No documentation available

Source Code

public DistanceComparator(int targetX, int targetY) {
this.targetX = targetX;
this.targetY = targetY;
}

Called Methods

No outgoing method calls

getPlayersList

Class: jfreerails.client.view.LeaderBoardJPanel

Documentation

/**
* This method initializes jList
*
* @return javax.swing.JList
*/

Source Code

/**
* This method initializes jList
*
* @return javax.swing.JList
*/
private JList getPlayersList() {
if (playersList == null) {
playersList = new JList();
playersList
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
playersList.setRequestFocusEnabled(false);
playersList.setEnabled(true);
Collections.sort(values);
playersList.setListData(values);
}
return playersList;
}

Called Methods

No outgoing method calls

size

Class: jfreerails.util.List1DImpl

Documentation

No documentation available

Source Code

public int size() {
return elementData.size();
}

Called Methods

No outgoing method calls

dumpImages

Class: jfreerails.client.renderer.TrackPieceRendererImpl

Documentation

No documentation available

Source Code

public void dumpImages(ImageManager imageManager) {
for (int i = 0; i < 512; i++) {
if (trackPieceIcons[i] != null) {
String fileName = generateFilename(i, getTrackTypeName());
imageManager.setImage(fileName, trackPieceIcons[i]);
}
}
}

addListDataListener

Class: jfreerails.client.view.DisplayModesComboBoxModels

Documentation

No documentation available

Source Code

public void addListDataListener(javax.swing.event.ListDataListener l) {
}

Called Methods

No outgoing method calls

TrainListCellRenderer

Class: jfreerails.client.view.TrainListCellRenderer

Documentation

No documentation available

Source Code

public TrainListCellRenderer() {
this.setOpaque(false);
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.train.EngineType

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object obj) {
if (!(obj instanceof EngineType))
return false;
EngineType other = (EngineType) obj;
return engineTypeName.equals(other.engineTypeName)
&& powerAtDrawbar == other.powerAtDrawbar && price.equals(other.price)
&& maintenance.equals(other.maintenance)
&& maxSpeed == other.maxSpeed;
}

refreshAll

Class: jfreerails.client.renderer.Unknown

Documentation

No documentation available

Source Code

public void refreshAll() {
}

Called Methods

No outgoing method calls

getActivity

Class: jfreerails.controller.MoveTrainPreMove

Documentation

No documentation available

Source Code

public SpeedTimeAndStatus.TrainActivity getActivity(ReadOnlyWorld w){
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
TrainMotion tm = ta.findCurrentMotion(Integer.MAX_VALUE);
return tm.getActivity();
}

hashCode

Class: jfreerails.world.track.TrackPieceImpl

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = configuration.hashCode();
result = 29 * result + trackType.hashCode();
result = 29 * result + ownerID;
result = 29 * result + ruleNumber;
return result;
}

writeToServer

Class: jfreerails.network.LocalConnection

Documentation

No documentation available

Source Code

public void writeToServer(FreerailsSerializable object) throws IOException {
if (status.isOpen()) {
synchronized (fromClient) {
fromClient.write(object);
fromClient.notifyAll();
}
} else {
throw new IOException();
}
}

assertTryUndoMoveFails

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

protected void assertTryUndoMoveFails(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryUndoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertTrue("Move went through when it should have failed", !ms.ok);
}

PositionOnTrack

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

public PositionOnTrack(int i) {
this.setValuesFromInt(i);
}

boundsContain

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public boolean boundsContain(SKEY k, int index) {
return (index >= 0 && index < this.size(k));
}

tiles

Class: jfreerails.world.train.PathOnTiles

Documentation

No documentation available

Source Code

public Iterator<ImPoint> tiles() {
return new Iterator<ImPoint>() {
int index = 0;
ImPoint next = start;
public boolean hasNext() {
return next != null;
}
public ImPoint next() {
if (next == null)
throw new NoSuchElementException();
ImPoint returnValue = next;
int x = next.x;
int y = next.y;
if (index < vectors.size()) {
Step s = vectors.get(index);
x += s.deltaX;
y += s.deltaY;
next = new ImPoint(x, y);
} else {
next = null;
}
index++;
return returnValue;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}

NextActivityMove

Class: jfreerails.move.NextActivityMove

Documentation

No documentation available

Source Code

public NextActivityMove(Activity activity, int index,
FreerailsPrincipal principal) {
this.activity = activity;
this.index = index;
this.principal = principal;
}

Called Methods

No outgoing method calls

sendItemRemoved

Class: jfreerails.network.specifics.MoveChainFork

Documentation

No documentation available

Source Code

private void sendItemRemoved(KEY key, int index, FreerailsPrincipal p) {
for (int i = 0; i < listListeners.size(); i++) {
WorldListListener l = listListeners.get(i);
l.itemRemoved(key, index, p);
}
}

RiverStyleTileRenderer

Class: jfreerails.client.renderer.RiverStyleTileRenderer

Documentation

No documentation available

Source Code

public RiverStyleTileRenderer(ImageManager imageManager, int[] rgbValues,
TerrainType tileModel) throws IOException {
super(tileModel, rgbValues);
this.setTileIcons(new Image[16]);
for (int i = 0; i < this.getTileIcons().length; i++) {
String fileName = generateRelativeFileName(i);
this.getTileIcons()[i] = imageManager.getImage(fileName);
}
}

processPreMove

Class: jfreerails.network.specifics.FreerailsClient

Documentation

No documentation available

Source Code

public void processPreMove(PreMove pm) {
Move m = committer.toServer(pm);
moveFork.processMove(m);
write(pm);
}

absolute2relativeTime

Class: jfreerails.world.top.ActivityIteratorImpl

Documentation

No documentation available

Source Code

public double absolute2relativeTime(double t) {
double dt = t - ant.startTime;
dt = Math.min(dt, ant.act.duration());
return dt;
}

IntLine

Class: jfreerails.world.common.IntLine

Documentation

/**
* Default constructor - defines a dot at 0,0.
*/

Source Code

/**
* Default constructor - defines a dot at 0,0.
*/
public IntLine() {
}

Called Methods

No outgoing method calls

getAmount

Class: jfreerails.world.common.Money

Documentation

No documentation available

Source Code

public long getAmount() {
return amount;
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.world.common.Money

Documentation

No documentation available

Source Code

@Override
public String toString() {
return df.format(amount);
}

Called Methods

No outgoing method calls

getCityName

Class: jfreerails.world.terrain.CityModel

Documentation

No documentation available

Source Code

public String getCityName() {
return name;
}

Called Methods

No outgoing method calls

actionPerformed

Class: experimental.Unknown

Documentation

No documentation available

Source Code

public void actionPerformed(ActionEvent arg0) {
dialogueBoxController.closeContent();
}

getUnderlyingList

Class: jfreerails.util.ListXDDiffs

Documentation

No documentation available

Source Code

abstract Object getUnderlyingList();

Called Methods

No outgoing method calls

swapScreens

Class: jfreerails.controller.ScreenHandler

Documentation

No documentation available

Source Code

public synchronized void swapScreens() {
if (!bufferStrategy.contentsLost()) {
bufferStrategy.show();
}
}

Called Methods

No outgoing method calls

createRelocatedPoint

Class: jfreerails.world.common.Step

Documentation

No documentation available

Source Code

public ImPoint createRelocatedPoint(ImPoint from) {
return new ImPoint(from.x + deltaX, from.y + deltaY);
}

Called Methods

No outgoing method calls

write

Class: jfreerails.util.CompressedOutputStream

Documentation

No documentation available

Source Code

@Override
public void write(byte[] b, int off, int len) throws IOException {
int written = 0;
do {
if (written >= len) {
break;
}
int toWrite = Math.min(len - written, buffer.length - writeIndex);
System.arraycopy(b, off + written, buffer, writeIndex, toWrite);
written += toWrite;
writeIndex += toWrite;
if (writeIndex >= buffer.length * 0.80000000000000004D) {
flush();
}
} while (true);
}

testBoundsOnSet1

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

public void testBoundsOnSet1() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
try {
assertEquals(2, diffs.size(0));
diffs.set(0, 2, String.valueOf(3));
fail();
} catch (Exception e) {
}
}

testWait

Class: jfreerails.network.LocalConnectionTest

Documentation

No documentation available

Source Code

public void testWait() {
try {
Money m = new Money(100);
localConnection.writeToServer(m);
// Since we have just added an object, there is no need to wait.
Object o = localConnection.waitForObjectFromClient();
assertEquals(m, o);
localConnection.writeToClient(m);
o = localConnection.waitForObjectFromServer();
assertEquals(m, o);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}

AddItemToSharedListMove

Class: jfreerails.move.AddItemToSharedListMove

Documentation

No documentation available

Source Code

protected AddItemToSharedListMove(SKEY key, int i,
FreerailsSerializable item) {
this.listKey = key;
this.index = i;
this.item = item;
}

Called Methods

No outgoing method calls

setServerControlInterface

Class: jfreerails.client.view.ServerControlModel

Documentation

No documentation available

Source Code

public void setServerControlInterface() {
// Check that there is a file to load..
saveGameAction.setEnabled(true);
Enumeration<Action> e = targetTicksPerSecondActions.getActions();
targetTicksPerSecondActions.setPerformActionOnSetSelectedItem(false);
while (e.hasMoreElements()) {
e.nextElement().setEnabled(true);
}
String[] mapNames = NewGameMessage2Server.getMapNames();
Action[] actions = new Action[mapNames.length];
for (int j = 0; j < actions.length; j++) {
actions[j] = new NewGameAction(mapNames[j]);
actions[j].setEnabled(true);
}
selectMapActions = new ActionAdapter(actions);
newGameAction.setEnabled(true);
}

getDefaultErrorHandler

Class: jfreerails.server.parser.CargoAndTerrainParser

Documentation

/**
* Creates default error handler used by this parser.
*
* @return org.xml.sax.ErrorHandler implementation
*
*/

Source Code

/**
* Creates default error handler used by this parser.
*
* @return org.xml.sax.ErrorHandler implementation
*
*/
protected ErrorHandler getDefaultErrorHandler() {
return new ErrorHandler() {
public void error(SAXParseException ex) throws SAXException {
if (context.isEmpty()) {
logger.severe("Missing DOCTYPE.");
}
throw ex;
}
public void fatalError(SAXParseException ex) throws SAXException {
throw ex;
}
public void warning(SAXParseException ex) throws SAXException {
// ignore
}
};
}

Called Methods

No outgoing method calls

testTiles

Class: jfreerails.world.train.PathOnTilesTest

Documentation

No documentation available

Source Code

public void testTiles() {
PathOnTiles path = new PathOnTiles(new ImPoint(5, 5), SOUTH_WEST,
NORTH_EAST);
Iterator<ImPoint> it = path.tiles();
assertEquals(new ImPoint(5, 5), it.next());
assertEquals(new ImPoint(4, 6), it.next());
assertEquals(new ImPoint(5, 5), it.next());
assertFalse(it.hasNext());
}

testNextVector

Class: jfreerails.controller.MoveTrainPreMove1stTest

Documentation

No documentation available

Source Code

public void testNextVector() {
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
Step actual = preMove.nextStep(world);
assertNotNull(actual);
// The train is at station A, so should head east to station B.
assertEquals(EAST, actual);
}

TileRendererListImpl

Class: jfreerails.client.renderer.TileRendererListImpl

Documentation

No documentation available

Source Code

public TileRendererListImpl(ArrayList<TileRenderer> t) {
tiles = new TileRenderer[t.size()];
for (int i = 0; i < t.size(); i++) {
tiles[i] = t.get(i);
}
}

Called Methods

No outgoing method calls

changedUpdate

Class: jfreerails.launcher.Unknown

Documentation

No documentation available

Source Code

public void changedUpdate(DocumentEvent e) {
validateInput();
}

testHashCodeAndEquals

Class: jfreerails.world.terrain.MiscTest

Documentation

No documentation available

Source Code

private void testHashCodeAndEquals(Serializable a) {
Serializable copy = Utils.cloneBySerialisation(a);
assertEquals(a, a);
assertEquals(a, copy);
assertEquals(a.hashCode(), copy.hashCode());
}

boundsContain

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public boolean boundsContain(FreerailsPrincipal p, KEY k, int index) {
if (!isPlayer(p)) {
return false;
} else if (index >= 0 && index < this.size(p, k)) {
return true;
} else {
return false;
}
}

run

Class: jfreerails.util.FlowRateInputStream

Documentation

No documentation available

Source Code

public void run() {
if (running || measureInterval == 0x7fffffffffffffffL) {
return;
}
running = true;
try {
do {
try {
Thread.currentThread();
Thread.sleep(measureInterval);
} catch (InterruptedException interruptedexception) {
}
if (!closeRequested) {
long totalByteReceivedCopy = totalByteReceived;
long byteSentThisTime = totalByteReceivedCopy
- previousTotalByteReceived;
previousTotalByteReceived = totalByteReceivedCopy;
byteReceivedCumul -= byteReceived[nextFree];
byteReceived[nextFree] = byteSentThisTime;
byteReceivedCumul += byteSentThisTime;
nextFree = (nextFree + 1) % byteReceived.length;
nbUsed = Math.min(byteReceived.length, nbUsed + 1);
if (showTrace) {
logger
.info(String
.valueOf(String
.valueOf((new StringBuffer(
"Stream "))
.append(streamName)
.append(
": Open duration = ")
.append(
(System
.currentTimeMillis() - openTimeMillis) / 1000D)
.append(
", Byte sent = ")
.append(
totalByteReceived)
.append(" (")
.append(
(int) (totalByteReceived / 1024D))
.append(
" Ko), current flow rate = ")
.append(
currentRateString())
.append(" Ko/s"))));
}
}
} while (!closeRequested);
} finally {
running = false;
}
}

doMove

Class: jfreerails.move.AddPlayerMove

Documentation

No documentation available

Source Code

public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (!ms.ok)
return ms;
int playerId = w.addPlayer(this.player2add);
// Sell the player 2 $500,000 bonds at 5% interest.
FreerailsPrincipal principal = player2add.getPrincipal();
w.addTransaction(principal, BondTransaction.issueBond(5));
//Issue stock
Money initialStockPrice = new Money(5);
Transaction t = StockTransaction.issueStock(playerId, 100000,
initialStockPrice);
w.addTransaction(principal, t);
return ms;
}

set

Class: jfreerails.util.List1DDiff

Documentation

No documentation available

Source Code

public void set(int i, T element) {
super.set(element, i);
}

getTrainLength

Class: jfreerails.controller.TrainStopsHandler

Documentation

No documentation available

Source Code

public int getTrainLength() {
TrainAccessor ta = new TrainAccessor(worldDiffs, principal, trainId);
return ta.getTrain().getLength();
}

doMove

Class: jfreerails.move.Move

Documentation

/**
* Executes this move on the specified world object.
*/

Source Code

/**
* Executes this move on the specified world object.
*/
MoveStatus doMove(World w, FreerailsPrincipal p);

Called Methods

No outgoing method calls

sharesOwnedByPublic

Class: jfreerails.controller.StockPriceCalculator

Documentation

No documentation available

Source Code

int sharesOwnedByPublic(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
FinancialDataGatherer gatherer = new FinancialDataGatherer(w, pr);
return gatherer.sharesHeldByPublic();
}

test1

Class: jfreerails.world.top.ItemsTransactionAggregatorTest

Documentation

No documentation available

Source Code

public void test1(){
World w = new WorldImpl();
Player player = new Player("name", 0);
w.addPlayer(player);
FreerailsPrincipal fp = w.getPlayer(0).getPrincipal();
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(w, fp);
aggregator.setCategory(TRACK);
int quant = aggregator.calculateQuantity();
assertEquals(0, quant);
Transaction t = new AddItemTransaction(Category.TRACK, 10, 5 , new Money(100));
w.addTransaction(fp, t);
quant = aggregator.calculateQuantity();
assertEquals(5, quant);
t = new AddItemTransaction(Category.TRACK, 10, 11 , new Money(200));
w.addTransaction(fp, t);
}

saveGame

Class: jfreerails.server.SavedGamesManagerImpl

Documentation

No documentation available

Source Code

public void saveGame(Serializable w, String s) throws IOException {
long startTime = System.currentTimeMillis();
logger.info("Saving game.. " + s);
FileOutputStream out = new FileOutputStream(s);
GZIPOutputStream zipout = new GZIPOutputStream(out);
ObjectOutputStream objectOut = new ObjectOutputStream(zipout);
objectOut.writeObject(ServerControlInterface.VERSION);
objectOut.writeObject(w);
objectOut.flush();
objectOut.close();
out.close();
long finishTime = System.currentTimeMillis();
long deltaTime = finishTime - startTime;
logger.info("done, " + deltaTime + "ms");
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.track.TrackConfiguration

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return configuration;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.controller.MessageStatus

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + (reason != null ? reason.hashCode() : 0);
result = 29 * result + (successful ? 1 : 0);
return result;
}

Called Methods

No outgoing method calls

testRemoveTrack

Class: jfreerails.move.ChangeTrackPieceCompositeMoveTest

Documentation

No documentation available

Source Code

public void testRemoveTrack() {
getWorld().set(ITEM.GAME_RULES, GameRules.NO_RESTRICTIONS);
TrackRule trackRule = (TrackRule) getWorld().get(SKEY.TRACK_RULES, 0);
assertBuildTrackSucceeds(new ImPoint(0, 5), east, trackRule);
assertBuildTrackSucceeds(new ImPoint(0, 6), east, trackRule);
assertBuildTrackSucceeds(new ImPoint(1, 6), east, trackRule);
assertBuildTrackSucceeds(new ImPoint(0, 7), east, trackRule);
assertBuildTrackSucceeds(new ImPoint(1, 7), east, trackRule);
assertBuildTrackSucceeds(new ImPoint(2, 7), east, trackRule);
// Remove only track piece built.
assertRemoveTrackSucceeds(new ImPoint(0, 5), east);
TrackConfiguration trackConfiguration = ((FreerailsTile) getWorld().getTile(0, 5))
.getTrackPiece().getTrackConfiguration();
TrackConfiguration expected = NullTrackPiece.getInstance().getTrackConfiguration();
assertEquals(expected,
trackConfiguration);
TrackConfiguration trackConfiguration2 = ((FreerailsTile) getWorld().getTile(1, 5))
.getTrackPiece().getTrackConfiguration();
assertEquals(expected,
trackConfiguration2);
}

sharesOwnedByOtherPlayers

Class: jfreerails.controller.StockPriceCalculator

Documentation

No documentation available

Source Code

int sharesOwnedByOtherPlayers(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
FinancialDataGatherer gatherer = new FinancialDataGatherer(w, pr);
int[] stakes = gatherer.getStockInThisRRs();
int total = 0;
for (int i = 0; i < stakes.length; i++) {
if(i != playerId){
total+= stakes[i];
}
}
return total;
}

initialize

Class: jfreerails.client.view.NetWorthGraphJPanel

Documentation

/**
* This method initializes this
*
*/

Source Code

/**
* This method initializes this
*
*/
private void initialize() {
yAxisLabel4 = new JLabel();
yAxisLabel3 = new JLabel();
yAxisLabel2 = new JLabel();
xAxisLabel1 = new JLabel();
xAxisLabel2 = new JLabel();
xAxisLabel3 = new JLabel();
title = new JLabel();
yAxisLabel1 = new JLabel();
this.setLayout(null);
this.setBackground(java.awt.Color.white);
this.setSize(444, 315);
title.setText("Net Worth");
title.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.PLAIN, 24));
title.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
title.setLocation(0, 0);
title.setSize(444, 43);
yAxisLabel1.setText("$25");
yAxisLabel1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
yAxisLabel3.setText("$999m");
yAxisLabel4.setText("$999M");
yAxisLabel4.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
yAxisLabel4.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
yAxisLabel3.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
yAxisLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
yAxisLabel2.setText("$50");
yAxisLabel2.setLocation(0, 167);
yAxisLabel2.setSize(40, 16);
yAxisLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
yAxisLabel2.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
yAxisLabel1.setLocation(0, 227);
yAxisLabel1.setSize(40, 16);
yAxisLabel3.setLocation(0, 107);
yAxisLabel3.setSize(40, 16);
yAxisLabel4.setLocation(0, 47);
yAxisLabel4.setSize(40, 16);
xAxisLabel3.setText("2000");
xAxisLabel3.setLocation(400, 300);
xAxisLabel3.setSize(40, 17);
xAxisLabel3.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
xAxisLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
xAxisLabel2.setText("1950");
xAxisLabel2.setLocation(210, 300);
xAxisLabel2.setSize(40, 17);
xAxisLabel2.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
xAxisLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
xAxisLabel1.setText("1900");
xAxisLabel1.setLocation(20, 300);
xAxisLabel1.setSize(40, 17);
xAxisLabel1.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
xAxisLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
this.add(xAxisLabel3, null);
this.add(xAxisLabel2, null);
this.add(xAxisLabel1, null);
yAxisLabel1.setFont(new java.awt.Font("Bookman Old Style",
java.awt.Font.BOLD, 10));
this.add(title, null);
this.add(yAxisLabel1, null);
this.add(yAxisLabel3, null);
this.add(yAxisLabel2, null);
this.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
if (null == submitButtonCallBack) {
System.err.println("mouseClicked");
} else {
submitButtonCallBack.actionPerformed(new ActionEvent(this,
0, null));
}
}
});
this.add(yAxisLabel4, null);
}

Called Methods

No outgoing method calls

getDirectoryContents

Class: jfreerails.util.ClassPath

Documentation

/**
* This method takes a top level classpath dir i.e. 'classes' or bin
*
* @param dir
*/

Source Code

/**
* This method takes a top level classpath dir i.e. 'classes' or bin
*
* @param dir
*/
protected LinkedList<String> getDirectoryContents(File dir) {
LinkedList<String> result = new LinkedList<String>();
// drill through contained dirs ... this is expected to be the
// 'classes' or 'bin' dir
File files[] = dir.listFiles();
if (null == files) {
logger.info("dir.listFiles() returned null for " + dir);
return result;
}
for (int i = 0; i < files.length; ++i) {
File f = files[i];
if (f.isDirectory()) {
result.addAll(getDirectoryContents("", f));
} else {
if (f.getName().endsWith(".class"))
result.add(convertToClass(f));
}
}
return result;
}

getOwner

Class: jfreerails.move.ChangeTrackPieceCompositeMove

Documentation

No documentation available

Source Code

public static int getOwner(FreerailsPrincipal p, ReadOnlyWorld w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
if (w.getPlayer(i).getPrincipal().equals(p)) {
return i;
}
}
throw new IllegalStateException();
}

calculateQuantitiesAndValues

Class: jfreerails.world.top.ItemsTransactionAggregator

Documentation

No documentation available

Source Code

public QuantitiesAndValues calculateQuantitiesAndValues() {
QuantitiesAndValues returnValue = new QuantitiesAndValues();
returnValue.values = super.calculateValues();
returnValue.quantities = this.quantities;
return returnValue;
}

getTrackPieceIcon

Class: jfreerails.client.renderer.TrackPieceRenderer

Documentation

No documentation available

Source Code

Image getTrackPieceIcon(int trackTemplate);

Called Methods

No outgoing method calls

AddTransactionMove

Class: jfreerails.move.AddTransactionMove

Documentation

No documentation available

Source Code

public AddTransactionMove(FreerailsPrincipal account, Transaction t) {
if (null == t) {
throw new NullPointerException();
}
principal = account;
transaction = t;
constrained = false;
}

Called Methods

No outgoing method calls

getTrackGraphicID

Class: jfreerails.world.track.EightRotationsOfTrackPieceProducer

Documentation

No documentation available

Source Code

private static int getTrackGraphicID(boolean[][] railsList) {
int trackGraphicNumber = 0;
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
if (railsList[x][y]) {
trackGraphicNumber = trackGraphicNumber
| (1 << (3 * y + x));
}
}
}
return trackGraphicNumber;
}

Called Methods

No outgoing method calls

start_TrackType

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void start_TrackType(final Attributes meta) throws SAXException {
int rGBvalue;
String rgbString = meta.getValue("RGBvalue");
rGBvalue = Integer.parseInt(rgbString, 16);
/*
* We need to change the format of the rgb value to the same one as used
* by the the BufferedImage that stores the map. See
* jfreerails.common.Map
*/
rGBvalue = new java.awt.Color(rGBvalue).getRGB();
TrackRule.TrackCategories category = TrackRule.TrackCategories
.valueOf(meta.getValue("category"));
boolean enableDoubleTrack = Boolean.valueOf(
meta.getValue("doubleTrack")).booleanValue();
String typeName = meta.getValue("type");
maxConsequ = Integer.parseInt(meta.getValue("maxConsecuativePieces"));
String stationRadiusString = meta.getValue("stationRadius");
int stationRadius;
if (null != stationRadiusString) {
stationRadius = Integer.parseInt(stationRadiusString);
} else {
stationRadius = 0;
}
String priceString = meta.getValue("price");
int price = Integer.parseInt(priceString);
String fixedCostString = meta.getValue("fixedCost");
int fixedCost;
if (null != fixedCostString) {
fixedCost = Integer.parseInt(fixedCostString);
} else {
fixedCost = 0;
}
String maintenanceString = meta.getValue("maintenance");
int maintenance = Integer.parseInt(maintenanceString);
trackRuleProperties = new TrackRuleProperties(rGBvalue,
enableDoubleTrack, typeName, category, stationRadius, price,
maintenance, fixedCost);
}

Called Methods

  • jfreerails.world.track.TrackRule.TrackCategories.valueOf (external)

clear

Class: jfreerails.util.LRUCache

Documentation

/**
* Clears the cache.
*/

Source Code

/**
* Clears the cache.
*/
public synchronized void clear() {
map.clear();
}

Called Methods

No outgoing method calls

send

Class: jfreerails.network.InetConnection

Documentation

No documentation available

Source Code

synchronized void send(FreerailsSerializable object) throws IOException {
objectOutputStream.writeObject(object);
flush();
}

isValid

Class: jfreerails.client.common.ImageManagerImpl

Documentation

No documentation available

Source Code

public static boolean isValid(String s) {
Matcher m = pattern.matcher(s);
return m.matches();
}

Called Methods

No outgoing method calls

propertyChange

Class: jfreerails.client.common.ModelRootListener

Documentation

No documentation available

Source Code

void propertyChange(ModelRoot.Property p, Object oldValue, Object newValue);

Called Methods

No outgoing method calls

getTrackBuilderMode

Class: jfreerails.controller.TrackMoveProducer

Documentation

No documentation available

Source Code

public BuildMode getTrackBuilderMode() {
return getBuildMode();
}

setStation

Class: jfreerails.client.view.StationInfoJPanel

Documentation

No documentation available

Source Code

public void setStation(int stationNumber) {
this.wi.gotoIndex(stationNumber);
display();
}

genException

Class: jfreerails.controller.ReportBugTextGenerator

Documentation

No documentation available

Source Code

private static Exception genException() {
Exception e = new Exception();
return e;
}

Called Methods

No outgoing method calls

startDocument

Class: jfreerails.server.parser.CargoAndTerrainParser

Documentation

/**
* This SAX interface method is implemented by the parser.
*
*/

Source Code

/**
* This SAX interface method is implemented by the parser.
*
*/
public final void startDocument() throws SAXException {
}

Called Methods

No outgoing method calls

getConsist

Class: jfreerails.world.train.TrainOrdersModel

Documentation

/**
* @return either (1) an array of cargo type ids or (2) null to represent
* 'no change'.
*/

Source Code

/**
* @return either (1) an array of cargo type ids or (2) null to represent
* 'no change'.
*/
public ImInts getConsist() {
return this.consist;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.cargo.CargoType

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object obj) {
if (!(obj instanceof CargoType))
return false;
CargoType other = (CargoType) obj;
return other.unitWeight == this.unitWeight && other.name.equals(name)
&& other.category.equals(category);
}

Called Methods

No outgoing method calls

processPreMove

Class: jfreerails.client.common.Unknown

Documentation

No documentation available

Source Code

public void processPreMove(PreMove pm) {
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.network.specifics.PreMoveAndMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = (m != null ? m.hashCode() : 0);
result = 29 * result + (pm != null ? pm.hashCode() : 0);
return result;
}

Called Methods

No outgoing method calls

generateMove

Class: jfreerails.controller.AddTrainPreMove

Documentation

/**
* Generates a move that does the following.
* <ol>
* <li>Adds the train</li>
* <li>Adds a cargo bundle to represent the cargo the train is
* carrying</li>
* <li>Adds a schedule for the train</li>
* <li>Adds transaction to pay for the train</li>
* <li>Init. the trains position and motion</li>
* </ol>
*
*
*/

Source Code

/**
* Generates a move that does the following.
* <ol>
* <li>Adds the train</li>
* <li>Adds a cargo bundle to represent the cargo the train is
* carrying</li>
* <li>Adds a schedule for the train</li>
* <li>Adds transaction to pay for the train</li>
* <li>Init. the trains position and motion</li>
* </ol>
*
*
*/
public Move generateMove(ReadOnlyWorld w) {
// Add cargo bundle.
int bundleId = w.size(principal, KEY.CARGO_BUNDLES);
ImmutableCargoBundle cargo = ImmutableCargoBundle.EMPTY_BUNDLE;
AddItemToListMove addCargoBundle = new AddItemToListMove(
KEY.CARGO_BUNDLES, bundleId, cargo, principal);
// Add schedule
for (int i = 0; i < schedule.getNumOrders(); i++) {
TrainOrdersModel order = schedule.getOrder(i);
if (!w.boundsContain(principal, KEY.STATIONS, order.stationId)) {
throw new ArrayIndexOutOfBoundsException(String.format("%d", order.stationId));
}
}
int scheduleId = w.size(principal, KEY.TRAIN_SCHEDULES);
AddItemToListMove addSchedule = new AddItemToListMove(
KEY.TRAIN_SCHEDULES, scheduleId, schedule, principal);
// Add train to train list.
TrainModel train = new TrainModel(engineTypeId, wagons, scheduleId,
bundleId);
int trainId = w.size(principal, KEY.TRAINS);
AddItemToListMove addTrain = new AddItemToListMove(KEY.TRAINS, trainId,
train, principal);
// Pay for train.
int quantity = 1;
/* Determine the price of the train. */
EngineType engineType = (EngineType) w.get(SKEY.ENGINE_TYPES,
engineTypeId);
Money price = engineType.getPrice();
Transaction transaction = new AddItemTransaction(
Transaction.Category.TRAIN, engineTypeId, quantity, new Money(
-price.getAmount()));
AddTransactionMove transactionMove = new AddTransactionMove(principal,
transaction);
// Setup and add train position.
PathOnTiles path = initPositionStep1(w);
TrainMotion motion = initPositionStep2(path);
Move addPosition = new AddActiveEntityMove(motion, trainId,
principal);
return new CompositeMove(addCargoBundle, addSchedule, addTrain,
transactionMove, addPosition);
}

removeLastActiveEntity

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public Activity removeLastActiveEntity(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
int lastID = activityLists.sizeD2(playerIndex) - 1;
Activity act = activityLists.removeLastD3(playerIndex, lastID).act;
activityLists.removeLastD2(playerIndex);
return act;
}

PositionOnTrack

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

private PositionOnTrack(int x, int y, Step direction) {
if (x > MAX_COORDINATE || x < 0) {
throw new IllegalArgumentException("x=" + x);
}
if (y > MAX_COORDINATE || y < 0) {
throw new IllegalArgumentException("y=" + y);
}
this.x = x;
this.y = y;
this.cameFrom = direction;
}

Called Methods

No outgoing method calls

fromBoolean

Class: jfreerails.world.common.ImInts

Documentation

No documentation available

Source Code

public static ImInts fromBoolean(boolean... i) {
int[] ii = new int[i.length];
for (int j = 0; j < i.length; j++) {
ii[j] = i[j] ? 1 : 0;
}
return new ImInts(ii);
}

Called Methods

No outgoing method calls

main

Class: experimental.CheckFreerailsSerializableClasses

Documentation

No documentation available

Source Code

public static void main(String[] args) {
immutableTypes.clear();
mutableTypes.clear();
immutableTypes.add(String.class);
// Class clazz = StationModel.class;
// System.err.println(overridesHashCodeAndEquals(clazz));
// System.out.println(clazz.isAnnotationPresent(InstanceControlled.class));
// Annotation[] ans = clazz.getAnnotations();
// for (Annotation an : ans) {
// System.err.println(an);
// }
// System.err.println(checkFields(clazz));
testAllClasses();
for (Class c : mutableTypes) {
System.err.println(c.getName());
}
}

generateMove

Class: jfreerails.server.TrackMaintenanceMoveGenerator

Documentation

No documentation available

Source Code

public static AddTransactionMove generateMove(World w,
FreerailsPrincipal principal, Transaction.Category category) {
if (TRACK_MAINTENANCE != category && STATION_MAINTENANCE != category) {
throw new IllegalArgumentException(String.valueOf(category));
}
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
w, principal);
aggregator.setCategory(TRACK);
long amount = 0;
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
long maintenanceCost = trackRule.getMaintenanceCost().getAmount();
// Is the track type the category we are interested in?
boolean rightType = TRACK_MAINTENANCE == category ? !trackRule
.isStation() : trackRule.isStation();
if (rightType) {
aggregator.setType(i);
amount += maintenanceCost * aggregator.calculateQuantity()
/ TrackConfiguration.LENGTH_OF_STRAIGHT_TRACK_PIECE;
}
}
Transaction t = new Bill(new Money(amount), category);
return new AddTransactionMove(principal, t);
}

getIpAddress

Class: jfreerails.network.specifics.AbstractFreerailsServerTestCase

Documentation

No documentation available

Source Code

protected String getIpAddress() {
return ipAddress;
}

Called Methods

No outgoing method calls

getProduction

Class: jfreerails.world.terrain.TerrainType

Documentation

No documentation available

Source Code

ImList<Production> getProduction();

Called Methods

No outgoing method calls

findStationName

Class: jfreerails.client.view.TrainSummaryJPanel

Documentation

No documentation available

Source Code

private String findStationName(int trainNum) {
TrainOrdersModel orders = null;
TrainOrdersListModel ordersList = new TrainOrdersListModel(w, trainNum,
principal);
for (int i = 0; i < ordersList.getSize(); ++i) {
TrainOrdersListElement element = (TrainOrdersListElement) ordersList
.getElementAt(i);
if (element.gotoStatus == TrainOrdersListModel.GOTO_NOW) {
orders = element.order;
break;
}
}
StationModel station = (StationModel) w.get(principal, KEY.STATIONS, orders
.getStationID());
return station.getStationName();
}

paint

Class: jfreerails.client.renderer.StationNamesRenderer

Documentation

No documentation available

Source Code

public void paint(Graphics2D g) {
int rectWidth;
int rectHeight;
int rectX;
int rectY;
float visibleAdvance;
float textX;
float textY;
StationModel tempStation;
String stationName;
int positionX;
int positionY;
Boolean showStationNames = (Boolean) modelRoot
.getProperty(ModelRoot.Property.SHOW_STATION_NAMES);
Boolean showStationBorders = (Boolean) modelRoot
.getProperty(ModelRoot.Property.SHOW_STATION_BORDERS);
FontRenderContext frc = g.getFontRenderContext();
TextLayout layout;
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
// draw station names onto map
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
while (wi.next()) { // loop over non null stations
tempStation = (StationModel) wi.getElement();
int x = tempStation.getStationX();
int y = tempStation.getStationY();
// First draw station sphere of influence
if (showStationBorders.booleanValue()) {
FreerailsTile tile = (FreerailsTile) w.getTile(x, y);
int radius = tile.getTrackPiece().getTrackRule().getStationRadius();
int diameterInPixels = (radius * 2 + 1) * 30;
int radiusX = (x - radius) * 30;
int radiusY = (y - radius) * 30;
g.setColor(Color.WHITE);
g.setStroke(dashed);
g.draw(new RoundRectangle2D.Double(radiusX, radiusY,
diameterInPixels, diameterInPixels, 10, 10));
}
// Then draw the station name.
if (showStationNames.booleanValue()) {
stationName = tempStation.getStationName();
positionX = (x * 30) + 15;
positionY = (y * 30) + 30;
layout = new TextLayout(stationName, font, frc);
visibleAdvance = layout.getVisibleAdvance();
rectWidth = (int) (visibleAdvance * 1.2);
rectHeight = (int) (fontSize * 1.5);
rectX = (positionX - (rectWidth / 2));
rectY = positionY;
g.setColor(bgColor);
g.fillRect(rectX, rectY, rectWidth, rectHeight);
textX = (positionX - (visibleAdvance / 2));
textY = positionY + fontSize + 1;
g.setColor(textColor);
layout.draw(g, textX, textY);
g.setStroke(new BasicStroke(1.0f));
// draw a border 1 pixel inside the edges of the rectangle
g.draw(new Rectangle(rectX + 1, rectY + 1, rectWidth - 3,
rectHeight - 3));
}
}
}
// end FOR loop
}

toString

Class: jfreerails.controller.OpenListEntry

Documentation

No documentation available

Source Code

@Override
public String toString() {
return "OpenListEntry{node=" + node + ", f=" + f + "}";
}

Called Methods

No outgoing method calls

assertDoThenUndoLeavesWorldUnchanged

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

protected void assertDoThenUndoLeavesWorldUnchanged(Move m) {
try {
World w = getWorld();
World before = (World) Utils.cloneBySerialisation(w);
assertEquals(before, w);
assertTrue(m.doMove(w, Player.AUTHORITATIVE).ok);
World after = (World) Utils.cloneBySerialisation(w);
assertFalse(after.equals(before));
boolean b = m.undoMove(w, Player.AUTHORITATIVE).ok;
assertTrue(b);
assertEquals(before, w);
} catch (Exception e) {
e.printStackTrace();
assertTrue(false);
}
}

setUp

Class: jfreerails.world.track.TrackPieceImplTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
w = MapFixtureFactory2.getCopy();
}

hashCode

Class: jfreerails.world.top.TestActivity

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return (int) duration;
}

Called Methods

No outgoing method calls

execute

Class: jfreerails.controller.Message2Server

Documentation

No documentation available

Source Code

MessageStatus execute(ServerControlInterface server);

Called Methods

No outgoing method calls

FlowRateInputStream

Class: jfreerails.util.FlowRateInputStream

Documentation

No documentation available

Source Code

public FlowRateInputStream(InputStream in, String streamName,
int measureDuration, int measureInterval) {
super(in);
byteReceivedCumul = 0L;
totalByteReceived = 0L;
previousTotalByteReceived = 0L;
openTimeMillis = System.currentTimeMillis();
nextFree = 0;
nbUsed = 0;
running = false;
closeRequested = false;
byteReceived = new long[measureDuration];
this.measureInterval = measureInterval;
this.streamName = streamName;
if (this.measureInterval == 0) {
showTrace = false;
this.measureInterval = 1000L;
} else {
showTrace = true;
}
(new Thread(this)).start();
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.train.ImmutableSchedule

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = nextScheduledOrder;
result = 29 * result + (hasPriorityOrders ? 1 : 0);
return result;
}

Called Methods

No outgoing method calls

previous

Class: jfreerails.world.top.NonNullElements

Documentation

No documentation available

Source Code

public boolean previous() {
int previousIndex = index; // this is used to look back.
do {
previousIndex--;
if (previousIndex < 0) {
return false;
}
} while (!testCondition(previousIndex));
row--;
index = previousIndex;
return true;
}

testSizeDx

Class: jfreerails.util.List3DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List3DDiff.sizeD1()'
*/
public void testSizeDx() {
assertEquals(0, diffs.sizeD1());
underlying.addD1();
assertEquals(1, diffs.sizeD1());
assertEquals(0, diffs.sizeD2(0));
underlying.addD2(0);
assertEquals(1, diffs.sizeD2(0));
assertEquals(0, diffs.sizeD3(0,0));
underlying.addD3(0,0, new Integer(4));
underlying.addD3(0,0, new Integer(4));
assertEquals(2, diffs.sizeD3(0,0));
}

getWagonImages

Class: jfreerails.client.renderer.RenderersRoot

Documentation

No documentation available

Source Code

TrainImages getWagonImages(int type);

Called Methods

No outgoing method calls

hasPrevious

Class: jfreerails.world.common.ActivityIterator

Documentation

No documentation available

Source Code

boolean hasPrevious();

Called Methods

No outgoing method calls

DialogueBoxTester

Class: experimental.DialogueBoxTester

Documentation

/** Creates new form TestGlassPanelMethod. */

Source Code

/** Creates new form TestGlassPanelMethod. */
private DialogueBoxTester() {
w = new WorldImpl(200, 200);
UntriedMoveReceiver dummyReceiver = new SimpleMoveReceiver(w);
modelRoot = new ModelRootImpl();
modelRoot.setMoveFork(new MoveChainFork());
modelRoot.setMoveReceiver(dummyReceiver);
WagonAndEngineTypesFactory wetf = new WagonAndEngineTypesFactory();
TileSetFactory tileFactory = new TileSetFactoryImpl();
tileFactory.addTerrainTileTypesList(w);
wetf.addTypesToWorld(w);
w.addPlayer(TEST_PLAYER);
try {
vl = new RenderersRootImpl(w, FreerailsProgressMonitor.NULL_INSTANCE);
} catch (IOException e) {
e.printStackTrace();
}
modelRoot.setup(w, TEST_PLAYER.getPrincipal());
ActionRoot actionRoot = new ActionRoot(modelRoot);
actionRoot.setup(modelRoot, vl);
dialogueBoxController = new DialogueBoxController(this, modelRoot);
actionRoot.setDialogueBoxController(dialogueBoxController);
dialogueBoxController.setDefaultFocusOwner(this);
int numberOfCargoTypes = w.size(SKEY.CARGO_TYPES);
StationModel bristol = new StationModel(10, 10, "Bristol",
numberOfCargoTypes, 0);
boolean[] demandArray = new boolean[numberOfCargoTypes];
// Make the stations demand all cargo..
for (int i = 0; i < demandArray.length; i++) {
demandArray[i] = true;
}
Demand4Cargo demand = new Demand4Cargo(demandArray);
bristol = new StationModel(bristol, demand);
w.add(TEST_PRINCIPAL, KEY.STATIONS, bristol);
w.add(TEST_PRINCIPAL, KEY.STATIONS, new StationModel(50, 100, "Bath",
numberOfCargoTypes, 0));
w.add(TEST_PRINCIPAL, KEY.STATIONS, new StationModel(40, 10, "Cardiff",
numberOfCargoTypes, 0));
w.add(TEST_PRINCIPAL, KEY.STATIONS, new StationModel(100, 10, "London",
numberOfCargoTypes, 0));
w.add(TEST_PRINCIPAL, KEY.STATIONS, new StationModel(90, 50, "Swansea",
numberOfCargoTypes, 0));
// Set up cargo bundle, for the purpose of this test code all the trains
// can share the
// same one.
MutableCargoBundle cb = new MutableCargoBundle();
cb.setAmount(new CargoBatch(0, 10, 10, 8, 0), 80);
cb.setAmount(new CargoBatch(0, 10, 10, 9, 0), 60);
cb.setAmount(new CargoBatch(1, 10, 10, 9, 0), 140);
cb.setAmount(new CargoBatch(3, 10, 10, 9, 0), 180);
cb.setAmount(new CargoBatch(5, 10, 10, 9, 0), 10);
w.add(TEST_PRINCIPAL, KEY.CARGO_BUNDLES, cb.toImmutableCargoBundle());
MutableSchedule schedule = new MutableSchedule();
TrainOrdersModel order = new TrainOrdersModel(0, new ImInts(0, 0, 0),
false, false);
TrainOrdersModel order2 = new TrainOrdersModel(1, new ImInts(1, 2, 0,
0, 0), true, false);
TrainOrdersModel order3 = new TrainOrdersModel(2, null, true, false);
schedule.setOrder(0, order);
schedule.setOrder(1, order2);
int scheduleID = w.add(TEST_PRINCIPAL, KEY.TRAIN_SCHEDULES, schedule
.toImmutableSchedule());
w.add(TEST_PRINCIPAL, KEY.TRAINS,
new TrainModel(0, new ImInts(0, 0), scheduleID));
schedule.setOrder(2, order2);
schedule.setOrder(3, order3);
scheduleID = w.add(TEST_PRINCIPAL, KEY.TRAIN_SCHEDULES,
schedule.toImmutableSchedule());
w.add(TEST_PRINCIPAL, KEY.TRAINS,
new TrainModel(1, new ImInts(1, 1), scheduleID));
schedule.setOrder(4, order2);
schedule.setOrderToGoto(3);
schedule.setPriorityOrders(order);
scheduleID = w.add(TEST_PRINCIPAL, KEY.TRAIN_SCHEDULES,
schedule.toImmutableSchedule());
w.add(TEST_PRINCIPAL, KEY.TRAINS,
new TrainModel(0, new ImInts(1, 2, 0), scheduleID));
final MyGlassPanel glassPanel = new MyGlassPanel();
dialogueBoxController.setup(modelRoot, vl);
initComponents();
glassPanel.setSize(800, 600);
this.addComponentListener(new JFrameMinimumSizeEnforcer(640, 480));
this.setSize(640, 480);
}

deltaAssets

Class: jfreerails.world.accounts.Bill

Documentation

No documentation available

Source Code

public Money deltaAssets() {
return amount.changeSign();
}

testRemoveLastD2

Class: jfreerails.util.List3DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List3DDiff.removeLastD2(int)'
*/
public void testRemoveLastD2() {
underlying.addD1();
underlying.addD2(0);
underlying.addD2(0);
underlying.addD2(0);
assertEquals(3, diffs.sizeD2(0));
diffs.removeLastD2(0);
assertEquals(2, diffs.sizeD2(0));
diffs.removeLastD2(0);
diffs.removeLastD2(0);
assertEquals(0, diffs.sizeD2(0));
try{
diffs.removeLastD2(0);
fail();
}catch (Exception e) {
}
}

show

Class: jfreerails.client.renderer.StationRadiusRenderer

Documentation

No documentation available

Source Code

public void show() {
if (!modelRoot
.is(Property.CURSOR_MODE, Value.PLACE_STATION_CURSOR_MODE)) {
modelRoot.setProperty(Property.PREVIOUS_CURSOR_MODE, modelRoot
.getProperty(Property.CURSOR_MODE));
modelRoot.setProperty(Property.CURSOR_MODE,
Value.PLACE_STATION_CURSOR_MODE);
modelRoot.setProperty(Property.IGNORE_KEY_EVENTS, Boolean.TRUE);
}
}

getBefore

Class: jfreerails.move.AddItemToListMove

Documentation

No documentation available

Source Code

public FreerailsSerializable getBefore() {
return null;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.common.Money

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object obj) {
if (obj instanceof Money) {
Money test = (Money) obj;
return test.amount == this.amount;
}
return false;
}

Called Methods

No outgoing method calls

createBrokerMenu

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

public JMenu createBrokerMenu() {
brokerMenu = new JMenu("Broker");
callBrokerJMenuItem = new JMenuItem("Call Broker");
callBrokerJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showBrokerScreen();
}
});
brokerMenu.add(callBrokerJMenuItem);
return brokerMenu;
}

suite

Class: jfreerails.move.ChangeTrackPieceMoveTest

Documentation

No documentation available

Source Code

public static junit.framework.Test suite() {
junit.framework.TestSuite testSuite = new junit.framework.TestSuite(
ChangeTrackPieceMoveTest.class);
return testSuite;
}

Called Methods

No outgoing method calls

tryDoMove

Class: jfreerails.move.AddTransactionMove

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.isPlayer(principal)) {
if (this.constrained) {
long bankBalance = w.getCurrentBalance(principal).getAmount();
long transactionAmount = this.transaction.deltaCash()
.getAmount();
long balanceAfter = bankBalance + transactionAmount;
if (transactionAmount < 0 && balanceAfter < 0) {
return MoveStatus.moveFailed("You can't afford that!");
}
}
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed(p.getName()
+ " does not have a bank account.");
}

validate

Class: jfreerails.client.top.QuickRGBTileRendererList

Documentation

No documentation available

Source Code

public boolean validate(ReadOnlyWorld world) {
return true;
}

Called Methods

No outgoing method calls

getMapSizeInPixels

Class: jfreerails.client.renderer.MapRenderer

Documentation

No documentation available

Source Code

Dimension getMapSizeInPixels();

Called Methods

No outgoing method calls

getQuantityOfCargo

Class: jfreerails.move.TransferCargoAtStationMove

Documentation

No documentation available

Source Code

public int getQuantityOfCargo(int cargoType) {
ImList<Move> moves = super.getMoves();
int quantity = CHANGE_AT_STATION_INDEX;
for (int i = CHANGE_AT_STATION_INDEX; i < moves.size(); i++) {
if (moves.get(i) instanceof AddTransactionMove) {
AddTransactionMove move = (AddTransactionMove) moves.get(i);
DeliverCargoReceipt receipt = (DeliverCargoReceipt) move
.getTransaction();
CargoBatch cb = receipt.getCb();
if (cb.getCargoType() == cargoType) {
quantity += receipt.getQuantity();
}
}
}
return quantity;
}

getSelection

Class: jfreerails.launcher.SelectMapJPanel

Documentation

No documentation available

Source Code

Selection getSelection() {
if( newmapsJList.getSelectedIndex() != -1 ){
savedmapsJList.setSelectedIndex(-1);
return Selection.NEW_GAME;
}
if(savedmapsJList.getSelectedIndex() != -1){
return Selection.LOAD_GAME;
}
return Selection.NONE;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
return o == this;
}

Called Methods

No outgoing method calls

GameCalendar

Class: jfreerails.world.common.GameCalendar

Documentation

No documentation available

Source Code

public GameCalendar(int ticksPerYear, int startYear) {
this.ticksPerYear = ticksPerYear;
this.startYear = startYear;
}

Called Methods

No outgoing method calls

createFacing

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

public static PositionOnTrack createFacing(int x, int y, Step direction) {
return new PositionOnTrack(x, y, direction.getOpposite());
}

sizeD2

Class: jfreerails.util.List3D

Documentation

No documentation available

Source Code

int sizeD2(int d1);

Called Methods

No outgoing method calls

WorldPrincipal

Class: jfreerails.world.player.WorldPrincipal

Documentation

No documentation available

Source Code

public WorldPrincipal(String name) {
super(-1);
this.principalName = name;
}

getType

Class: jfreerails.controller.CargoElementObject

Documentation

No documentation available

Source Code

public int getType() {
return type;
}

Called Methods

No outgoing method calls

getAfter

Class: jfreerails.move.RemoveItemFromListMove

Documentation

No documentation available

Source Code

public FreerailsSerializable getAfter() {
return null;
}

Called Methods

No outgoing method calls

showNetworthGraphActionPerformed

Class: experimental.DialogueBoxTester

Documentation

No documentation available

Source Code

private void showNetworthGraphActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showNetworthGraphActionPerformed
dialogueBoxController.showNetworthGraph();
}// GEN-LAST:event_showNetworthGraphActionPerformed

testMove

Class: jfreerails.move.ChangeTileMoveTest

Documentation

No documentation available

Source Code

@Override
public void testMove() {
Point p = new Point(10, 10);
TerrainTile tile = (TerrainTile) world.getTile(10, 10);
assertTrue(tile.getTerrainTypeID() != 5);
ChangeTileMove move = new ChangeTileMove(world, p, 5);
MoveStatus ms = move.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.message, ms.ok);
tile = (TerrainTile) world.getTile(10, 10);
assertTrue(tile.getTerrainTypeID() == 5);
}

testRemoveLastD3

Class: jfreerails.util.List3DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List3DDiff.removeLastD3(int, int)'
*/
public void testRemoveLastD3() {
underlying.addD1();
underlying.addD2(0);
underlying.addD3(0,0, new Integer(1));
underlying.addD3(0,0, new Integer(2));
underlying.addD3(0,0, new Integer(3));
assertEquals(3, diffs.sizeD3(0,0));
diffs.removeLastD3(0, 0);
assertEquals(2, diffs.sizeD3(0,0));
diffs.removeLastD3(0, 0);
assertEquals(1, diffs.sizeD3(0,0));
diffs.removeLastD3(0, 0);
assertEquals(0, diffs.sizeD3(0,0));
try{
diffs.removeLastD3(0, 0);
fail();
}catch (Exception e) {
}
}

equals

Class: jfreerails.network.specifics.PreMoveAndMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof PreMoveAndMove))
return false;
final PreMoveAndMove preMoveAndMove = (PreMoveAndMove) o;
if (m != null ? !m.equals(preMoveAndMove.m)
: preMoveAndMove.m != null)
return false;
if (pm != null ? !pm.equals(preMoveAndMove.pm)
: preMoveAndMove.pm != null)
return false;
return true;
}

Called Methods

No outgoing method calls

getEdgeCost

Class: jfreerails.controller.Map

Documentation

No documentation available

Source Code

public int getEdgeCost() {
return nodes[position].distances[branch];
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.common.GameCalendar

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = ticksPerYear;
result = 29 * result + startYear;
return result;
}

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.view.TrainListJPanel

Documentation

No documentation available

Source Code

public void setup(final ModelRoot mr, RenderersRoot vl,
Action closeAction) {
world = mr.getWorld();
trainSummaryJPanel1.setup(mr, vl, null);
if (rhsjTabPane) {
jList1.setModel(new World2ListModelAdapter(mr.getWorld(),
KEY.TRAINS, mr.getPrincipal()));
TrainListCellRenderer trainView = new TrainListCellRenderer(mr, vl);
jList1.setCellRenderer(trainView);
trainView.setHeight(trainViewHeight);
}
ActionListener[] oldListeners = closeJButton.getActionListeners();
for (int i = 0; i < oldListeners.length; i++) {
closeJButton.removeActionListener(oldListeners[i]);
}
closeJButton.addActionListener(closeAction);
ListSelectionListener[] old = jList1.getListSelectionListeners();
for(ListSelectionListener x : old){
jList1.removeListSelectionListener(x);
}
jList1.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int id = getSelectedTrainID();
mr.setProperty(ModelRoot.Property.SELECTED_TRAIN, id);
}
});
principal = mr.getPrincipal();
ModelRootImpl mri = (ModelRootImpl) mr;
mri.addPropertyChangeListener(this);
}

getTargetTicksPerSecond

Class: jfreerails.client.view.ServerControlModel

Documentation

No documentation available

Source Code

public int getTargetTicksPerSecond() {
ReadOnlyWorld world = modelRoot.getWorld();
return ((GameSpeed) world.get(ITEM.GAME_SPEED)).getSpeed();
}

getNewInstance

Class: jfreerails.world.train.TrainModel

Documentation

No documentation available

Source Code

public TrainModel getNewInstance(int newEngine, ImInts newWagons) {
return new TrainModel(newEngine, newWagons, this.getScheduleID(), this
.getCargoBundleID());
}

checkTile

Class: jfreerails.client.renderer.AbstractTileRenderer

Documentation

No documentation available

Source Code

int checkTile(int x, int y, ReadOnlyWorld w) {
int match = 0;
if (((x < w.getMapWidth()) && (x >= 0)) && (y < w.getMapHeight())
&& (y >= 0)) {
for (int i = 0; i < typeNumbers.length; i++) {
TerrainTile tt = (TerrainTile) w.getTile(x, y);
if (tt.getTerrainTypeID() == typeNumbers[i]) {
match = 1;
// A match
}
}
} else {
match = 1; // A match
/*
* If the tile we are checking is off the map, let it be a match.
* This stops coast appearing where the ocean meets the map edge.
*/
}
return match;
}

getCategory

Class: jfreerails.world.cargo.CargoType

Documentation

No documentation available

Source Code

public Categories getCategory() {
return category;
}

Called Methods

No outgoing method calls

addSteps

Class: jfreerails.world.train.PathOnTiles

Documentation

No documentation available

Source Code

public PathOnTiles addSteps(Step... newSteps) {
int oldLength = vectors.size();
Step[] newPath = new Step[oldLength + newSteps.length];
for (int i = 0; i < oldLength; i++) {
newPath[i] = vectors.get(i);
}
for (int i = 0; i < newSteps.length; i++) {
newPath[i + oldLength] = newSteps[i];
}
return new PathOnTiles(start, newPath);
}

getUnderlyingList

Class: jfreerails.util.List1DDiff

Documentation

No documentation available

Source Code

@Override
Object getUnderlyingList() {
return underlyingList;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.move.ChangeTrackPieceMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = (trackPieceBefore != null ? trackPieceBefore.hashCode() : 0);
result = 29 * result
+ (trackPieceAfter != null ? trackPieceAfter.hashCode() : 0);
result = 29 * result + location.hashCode();
return result;
}

testNextSegment

Class: jfreerails.controller.ToAndFroPathIteratorTest

Documentation

No documentation available

Source Code

public void testNextSegment() {
List<Point> l = new ArrayList<Point>();
IntLine line = new IntLine();
l.add(new Point(0, 1));
l.add(new Point(10, 11));
l.add(new Point(20, 22));
FreerailsPathIterator it = new ToAndFroPathIterator(l);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(0, 1, 10, 11, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(10, 11, 20, 22, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(20, 22, 10, 11, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(10, 11, 0, 1, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(0, 1, 10, 11, line);
assertTrue(it.hasNext());
it.nextSegment(line);
assertLineEquals(10, 11, 20, 22, line);
}

tryDoMove

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(Move m) {
return this.moveReceiver.tryDoMove(m);
}

setUp

Class: jfreerails.client.view.TrainScheduleJPanelTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
//jpanel = new TrainScheduleJPanel();
//World w = MapFixtureFactory2.getCopy();
}

Called Methods

No outgoing method calls

TrackSection

Class: jfreerails.world.track.TrackSection

Documentation

No documentation available

Source Code

public TrackSection(final Step step, final ImPoint tile) {
ImPoint otherTile = Step.move(tile, step);
if(tile.compareTo(otherTile) > 0){
this.step = step.getOpposite();
this.tile = otherTile;
}else{
this.step = step;
this.tile = tile;
}
}

paintBufferRectangle

Class: jfreerails.client.renderer.SquareTileBackgroundRenderer

Documentation

No documentation available

Source Code

@Override
protected void paintBufferRectangle(int x, int y, int width, int height) {
// Fix for bug [ 1303162 ]
// If the buffer hasn't been set yet, don't try and refresh it!
if (null != super.backgroundBuffer) {
Graphics gg = bg.create();
gg.setClip(x, y, width, height);
gg.translate(-bufferRect.x, -bufferRect.y);
mapView.paintRect(gg, bufferRect);
}
}

initAutomaton

Class: jfreerails.server.TrainPathFinder

Documentation

No documentation available

Source Code

public void initAutomaton(MoveReceiver newMr) {
this.mr = newMr;
}

Called Methods

No outgoing method calls

lastMotion

Class: jfreerails.controller.MoveTrainPreMove

Documentation

No documentation available

Source Code

private TrainMotion lastMotion(ReadOnlyWorld w) {
ActivityIterator ai = w.getActivities(principal, trainID);
ai.gotoLastActivity();
TrainMotion lastMotion = (TrainMotion) ai.getActivity();
return lastMotion;
}

FreerailsTile

Class: jfreerails.world.track.FreerailsTile

Documentation

No documentation available

Source Code

private FreerailsTile(int terrainType) {
this.terrainType = terrainType;
this.trackPiece = NullTrackPiece.getInstance();
}

LoadGameAction

Class: jfreerails.client.view.LoadGameAction

Documentation

No documentation available

Source Code

public LoadGameAction() {
putValue(NAME, "Load Game");
putValue(MNEMONIC_KEY, new Integer(76));
}

Called Methods

No outgoing method calls

addD1

Class: jfreerails.util.List3D

Documentation

No documentation available

Source Code

int addD1();

Called Methods

No outgoing method calls

write

Class: jfreerails.network.specifics.ServerGameModel

Documentation

No documentation available

Source Code

void write(ObjectOutputStream objectOut) throws IOException;

Called Methods

No outgoing method calls

getIndex

Class: jfreerails.world.top.WorldIterator

Documentation

/**
* Returns the index of the element the cursor is pointing to. The value
* returned is index you would need to use in
* <code>World.get(KEY key, int index)</code> to retrieve the same element
* as is returned by <code>getElement()</code>
*/

Source Code

/**
* Returns the index of the element the cursor is pointing to. The value
* returned is index you would need to use in
* <code>World.get(KEY key, int index)</code> to retrieve the same element
* as is returned by <code>getElement()</code>
*/
int getIndex();

Called Methods

No outgoing method calls

read

Class: jfreerails.util.CompressedInputStream

Documentation

No documentation available

Source Code

@Override
public int read(byte[] b, int off, int len) throws IOException {
if (maxReadIndex - readIndex == 0 && !readNextBuffer()) {
return -1;
}
int read = 0;
for (int i = 0; i < len && available() > 0;) {
b[off + i] = (byte) read();
i++;
read++;
}
return read;
}

addTransaction

Class: jfreerails.world.top.World

Documentation

/**
* Adds the specified transaction to the specified principal's bank account.
*/

Source Code

/**
* Adds the specified transaction to the specified principal's bank account.
*/
void addTransaction(FreerailsPrincipal p, Transaction t);

Called Methods

No outgoing method calls

TrainStopsHandlerTest

Class: jfreerails.controller.TrainStopsHandlerTest

Documentation

No documentation available

Source Code

public TrainStopsHandlerTest() {
}

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.view.MainMapAndOverviewMapMediator

Documentation

No documentation available

Source Code

public void setup(JComponent omv, JViewport v, JComponent mm, Rectangle rect) {
currentVisRect = rect;
overviewMapJPanel = omv;
viewport = v;
mainMap = mm;
overviewMapJPanel.addMouseMotionListener(this);
overviewMapJPanel.addMouseListener(this);
viewport.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(ChangeEvent e) {
updateObservedRect();
}
});
overviewMapJPanel
.addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(
java.awt.event.ComponentEvent evt) {
updateObservedRect();
}
@Override
public void componentShown(java.awt.event.ComponentEvent evt) {
updateObservedRect();
}
});
}

setControlsEnabled

Class: jfreerails.launcher.ClientOptionsJPanel

Documentation

No documentation available

Source Code

public void setControlsEnabled(boolean enabled) {
windowedButton.setEnabled(enabled);
fullScreenButton.setEnabled(enabled);
fixedSizeButton.setEnabled(enabled);
if (fullScreenButton.isSelected()) {
jList1.setEnabled(enabled);
}
}

Called Methods

No outgoing method calls

testHasNext

Class: jfreerails.controller.FlatTrackExplorerTest

Documentation

No documentation available

Source Code

public void testHasNext() {
setUp();
FlatTrackExplorer explorer = new FlatTrackExplorer(world,
PositionOnTrack.createComingFrom(10, 10, Step.EAST));
assertTrue(explorer.hasNextEdge());
}

insertUpdate

Class: jfreerails.launcher.Unknown

Documentation

No documentation available

Source Code

public void insertUpdate(DocumentEvent e) {
validateInput();
}

componentMoved

Class: jfreerails.controller.JFrameMinimumSizeEnforcer

Documentation

No documentation available

Source Code

public void componentMoved(ComponentEvent arg0) {
}

Called Methods

No outgoing method calls

setbackgroundBuffer

Class: jfreerails.client.renderer.BufferedTiledBackgroundRenderer

Documentation

No documentation available

Source Code

private void setbackgroundBuffer(int w, int h) {
// Releases VRAM used by backgroundBuffer.
if (backgroundBuffer != null) {
backgroundBuffer.flush();
}
// Create new backgroundBuffer.
backgroundBuffer = defaultConfig.createCompatibleVolatileImage(w, h);
bufferRect.height = backgroundBuffer.getHeight(null);
bufferRect.width = backgroundBuffer.getWidth(null);
resetGraphics();
bg.clearRect(0, 0, w, h);
refreshBackground();
}

gotoStationJMenuItemActionPerformed

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void gotoStationJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_gotoStationJMenuItemActionPerformed
MutableSchedule s = getSchedule();
int i = orders.getSelectedIndex();
s.setOrderToGoto(i);
sendUpdateMove(s);
}// GEN-LAST:event_gotoStationJMenuItemActionPerformed

setMessage

Class: jfreerails.launcher.GUIClient

Documentation

No documentation available

Source Code

public void setMessage(String s) {
System.out.println(s);
}

Called Methods

No outgoing method calls

assertUndoMoveIsOk

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

protected void assertUndoMoveIsOk(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.undoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals(MoveStatus.MOVE_OK, ms);
}

removeListDataListener

Class: jfreerails.client.view.DisplayModesComboBoxModels

Documentation

No documentation available

Source Code

public void removeListDataListener(javax.swing.event.ListDataListener l) {
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.controller.MoveTrainPreMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = trainID;
result = 29 * result + principal.hashCode();
return result;
}

Called Methods

No outgoing method calls

Person

Class: jfreerails.client.view.Person

Documentation

No documentation available

Source Code

public Person(String name){
this.name = name;
}

Called Methods

No outgoing method calls

loadGame

Class: jfreerails.server.SavedGamesManagerImpl

Documentation

No documentation available

Source Code

public Serializable loadGame(String name) throws IOException {
long startTime = System.currentTimeMillis();
logger.info("Loading game.. " + name);
FileInputStream in = new FileInputStream(name);
GZIPInputStream zipin = new GZIPInputStream(in);
ObjectInputStream objectIn = new ObjectInputStream(zipin);
String version_string;
try {
version_string = (String) objectIn.readObject();
if (!ServerControlInterface.VERSION.equals(version_string)) {
throw new IOException(version_string);
}
Serializable game = (Serializable) objectIn.readObject();
/**
* load player private data
*/
// for (int i = 0; i < world.getNumberOfPlayers(); i++) {
// Player player = world.getPlayer(i);
// player.loadSession(objectIn);
// }
long finishTime = System.currentTimeMillis();
long deltaTime = finishTime - startTime;
logger.info("done, " + deltaTime + "ms");
return game;
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new IOException(e.getMessage());
} catch (InvalidClassException e) {
// e.printStackTrace();
throw new IOException(e.getMessage());
}
}

Called Methods

No outgoing method calls

testMove2

Class: jfreerails.controller.MoveTrainPreMove1stTest

Documentation

No documentation available

Source Code

public void testMove2() {
MoveStatus ms;
Move m;
setupLoopOfTrack();
TrainAccessor ta = new TrainAccessor(world, principal, 0);
TrainMotion tm = ta.findCurrentMotion(3);
assertEquals(0d, tm.duration());
PathOnTiles expected = new PathOnTiles(new ImPoint(5, 5), SOUTH_WEST);
assertEquals(expected, tm.getPath());
PositionOnTrack pot = tm.getFinalPosition();
int x = pot.getX();
assertEquals(4, x);
int y = pot.getY();
assertEquals(6, y);
assertEquals(SOUTH_WEST, pot.facing());
MoveTrainPreMove moveTrain = new MoveTrainPreMove(0, principal);
assertEquals(NORTH_EAST, moveTrain.nextStep(world));
m = moveTrain.generateMove(world);
ms = m.doMove(world, principal);
assertTrue(ms.ok);
TrainMotion tm2 = ta.findCurrentMotion(3);
assertFalse(tm.equals(tm2));
expected = new PathOnTiles(new ImPoint(5, 5), SOUTH_WEST, NORTH_EAST);
assertEquals(expected, tm2.getPath());
assertTrue(tm2.duration() > 3d);
// The expected value is 3.481641930846211, found from
// stepping thu code in debugger.
assertTrackHere(tm2.getTiles(tm2.duration()));
pot = tm2.getFinalPosition();
assertEquals(4, x);
assertEquals(6, y);
// assertEquals(SOUTH, pot.facing());
assertTrackHere(x, y);
assertEquals(EAST, moveTrain.nextStep(world));
MoveTrainPreMove2ndTest.incrTime(world, principal);
m = moveTrain.generateMove(world);
ms = m.doMove(world, principal);
assertTrue(ms.ok);
TrainMotion tm3 = ta.findCurrentMotion(100);
assertFalse(tm3.equals(tm2));
expected = new PathOnTiles(new ImPoint(4, 6), NORTH_EAST, EAST);
assertEquals(expected, tm3.getPath());
assertTrackHere(tm3.getTiles(tm3.duration()));
assertTrackHere(tm3.getTiles(tm3.duration() / 2));
assertTrackHere(tm3.getTiles(0));
assertTrackHere(tm3.getPath());
assertEquals(SOUTH_EAST, moveTrain.nextStep(world));
MoveTrainPreMove2ndTest.incrTime(world, principal);
m = moveTrain.generateMove(world);
ms = m.doMove(world, principal);
assertTrue(ms.ok);
}

actionPerformed

Class: jfreerails.client.view.StationCancelAction

Documentation

No documentation available

Source Code

public void actionPerformed(ActionEvent e) {
stationBuildAction.setEnabled(false);
}

Called Methods

No outgoing method calls

assertOkAndRepeatable

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

protected void assertOkAndRepeatable(Move m) {
assertSetupHasBeenCalled();
// Do move
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
// Since it leaves the world unchanged it should also be
// possible to undo it repeatably
assertTryUndoMoveIsOk(m);
assertUndoMoveIsOk(m);
assertTryUndoMoveIsOk(m);
assertUndoMoveIsOk(m);
}

paintRect

Class: jfreerails.client.renderer.MapLayerRenderer

Documentation

No documentation available

Source Code

void paintRect(Graphics g, Rectangle visibleRect);

Called Methods

No outgoing method calls

actionPerformed

Class: jfreerails.client.view.Unknown

Documentation

No documentation available

Source Code

public void actionPerformed(ActionEvent arg0) {
WorldIterator wi = new NonNullElements(KEY.STATIONS, modelRoot
.getWorld(), modelRoot.getPrincipal());
if (wi.next()) {
StationModel station = (StationModel) wi.getElement();
ImList<PlannedTrain> before = station.getProduction();
int engineType = selectEngine.getEngineType();
int[] wagonTypes = selectWagons.getWagons();
ImList<PlannedTrain> after = new ImList<PlannedTrain>(
new PlannedTrain(engineType, wagonTypes));
Move m = new ChangeProductionAtEngineShopMove(before, after, wi
.getIndex(), modelRoot.getPrincipal());
modelRoot.doMove(m);
}
closeContent();
}

showExitDialog

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

// Shows the Exit Dialog -- @author SonnyZ
public void showExitDialog() {
ConfirmExitJPanel bs = new ConfirmExitJPanel();
bs.setup(this.modelRoot, vl, this.closeCurrentDialogue);
this.showContent(bs);
}

get

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

public T get(int d1, int d2, int d3) {
return super.get(d1, d2, d3);
}

getCoordinateOnSegment

Class: jfreerails.world.train.PathWalkerImpl

Documentation

No documentation available

Source Code

private int getCoordinateOnSegment(double distanceAlongSegment,
int coordinate1, int coordinate2) {
double segmentLength = this.currentSegment.getLength();
double delta = 0;
if (0 != segmentLength) {
delta = (coordinate2 - coordinate1) * distanceAlongSegment
/ segmentLength;
}
return coordinate1 + (int) delta;
}

SquareTileBackgroundRenderer

Class: jfreerails.client.renderer.SquareTileBackgroundRenderer

Documentation

No documentation available

Source Code

public SquareTileBackgroundRenderer(MapLayerRenderer mv) {
if (null == mv) {
throw new NullPointerException();
}
this.mapView = mv;
}

Called Methods

No outgoing method calls

setupItems

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

void setupItems() {
this.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
time = new GameTime(0);
this.set(ITEM.ECONOMIC_CLIMATE, EconomicClimate.MODERATION);
}

refreshTile

Class: jfreerails.client.renderer.SquareTileBackgroundRenderer

Documentation

No documentation available

Source Code

public void refreshTile(int x, int y) {
// The backgroundBuffer gets created on the first call to
// backgroundBuffer.paintRect(..)
// so we need a check here to avoid a null pointer exception.
if (null != super.backgroundBuffer) {
Graphics gg = bg.create();
gg.translate(-bufferRect.x, -bufferRect.y);
mapView.paintTile(gg, x, y);
}
}

getBuildTrackStrategy

Class: jfreerails.controller.TrackMoveProducer

Documentation

No documentation available

Source Code

public BuildTrackStrategy getBuildTrackStrategy() {
return (BuildTrackStrategy) mr.getProperty(Property.BUILD_TRACK_STRATEGY);
}

getDuration

Class: jfreerails.world.common.ActivityIterator

Documentation

No documentation available

Source Code

double getDuration();

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.network.specifics.SaveGameMessage2Server

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + filename.hashCode();
return result;
}

Called Methods

No outgoing method calls

MapCustomizer

Class: jfreerails.server.MapCustomizer

Documentation

No documentation available

Source Code

public MapCustomizer(World w) {
this.w = w;
MoveExecutor me = new SimpleMoveExecutor(w, 0);
ModelRoot mr = new ModelRootImpl();
producer = new TrackMoveProducer(me, w, mr);
FreerailsPrincipal principal = w.getPlayer(0).getPrincipal();
pathFinder = new TrackPathFinder(w, principal);
stationBuilder = new StationBuilder(me);
int terminalTypeID = stationBuilder.getTrackTypeID("terminal");
stationBuilder.setStationType(terminalTypeID);
bts = BuildTrackStrategy.getDefault(w);
}

setText

Class: jfreerails.controller.UnexpectedExceptionForm

Documentation

No documentation available

Source Code

public void setText(String s){
copyableTextJPanel1.setText(s);
}

refreshAll

Class: jfreerails.client.renderer.BlankMapRenderer

Documentation

No documentation available

Source Code

public void refreshAll() {
// do nothing
}

Called Methods

No outgoing method calls

tryUndoMove

Class: jfreerails.move.AddActiveEntityMove

Documentation

No documentation available

Source Code

public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int expectedSize = index + 1;
if (expectedSize != w.size(principal))
return MoveStatus
.moveFailed("(index + 1) != w.size(listKey, principal)");
ActivityIterator ai = w.getActivities(principal, index);
if (ai.hasNext())
return MoveStatus
.moveFailed("There should be exactly one activity!");
Activity act = ai.getActivity();
if (!act.equals(activity))
return MoveStatus.moveFailed("Expected " + activity.toString()
+ " but found " + act.toString());
return MoveStatus.MOVE_OK;
}

getType

Class: jfreerails.world.top.ItemsTransactionAggregator

Documentation

No documentation available

Source Code

public int getType() {
return type;
}

Called Methods

No outgoing method calls

initComponents

Class: jfreerails.client.top.ClientJFrame

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
rhsjPanel = new javax.swing.JPanel();
mapOverview = gUIComponentFactory.createOverviewMap();
trainsJTabPane1 = gUIComponentFactory.createTrainsJTabPane();
lhsjPanel = new javax.swing.JPanel();
mainMapView = gUIComponentFactory.createMainMap();
statusjPanel = new javax.swing.JPanel();
datejLabel = gUIComponentFactory.createDateJLabel();
cashjLabel = gUIComponentFactory.createCashJLabel();
jMenuBar1 = new javax.swing.JMenuBar();
gameMenu = gUIComponentFactory.createGameMenu();
buildMenu = gUIComponentFactory.createBuildMenu();
BrokerMenu1 = gUIComponentFactory.createBrokerMenu();
displayMenu = gUIComponentFactory.createDisplayMenu();
reportsMenu = gUIComponentFactory.createReportsMenu();
helpMenu = gUIComponentFactory.createHelpMenu();
getContentPane().setLayout(new java.awt.GridBagLayout());
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
rhsjPanel.setLayout(new java.awt.GridBagLayout());
rhsjPanel.add(mapOverview, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
rhsjPanel.add(trainsJTabPane1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
getContentPane().add(rhsjPanel, gridBagConstraints);
lhsjPanel.setLayout(new java.awt.GridBagLayout());
mainMapView.setAlignmentX(0.0F);
mainMapView.setAlignmentY(0.0F);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
lhsjPanel.add(mainMapView, gridBagConstraints);
statusjPanel.add(datejLabel);
statusjPanel.add(cashjLabel);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
lhsjPanel.add(statusjPanel, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(lhsjPanel, gridBagConstraints);
gameMenu.setText("Game");
jMenuBar1.add(gameMenu);
buildMenu.setText("Build");
jMenuBar1.add(buildMenu);
BrokerMenu1.setText("Broker");
jMenuBar1.add(BrokerMenu1);
displayMenu.setText("Display");
jMenuBar1.add(displayMenu);
reportsMenu.setText("Reports");
jMenuBar1.add(reportsMenu);
helpMenu.setText("Help");
jMenuBar1.add(helpMenu);
setJMenuBar(jMenuBar1);
pack();
}// GEN-END:initComponents

initComponents

Class: jfreerails.launcher.ConnectedPlayersJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
title = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
setLayout(new java.awt.GridBagLayout());
title.setText("Connected Players");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(title, gridBagConstraints);
jList1.setModel(new javax.swing.AbstractListModel() {
private static final long serialVersionUID = 1L;
String[] strings = { "No players are logged on!" };
public int getSize() {
return strings.length;
}
public Object getElementAt(int i) {
return strings[i];
}
});
jScrollPane1.setViewportView(jList1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}// GEN-END:initComponents

Called Methods

No outgoing method calls

FinancialMoveProducer

Class: jfreerails.controller.FinancialMoveProducer

Documentation

No documentation available

Source Code

FinancialMoveProducer(ReadOnlyWorld row) {
}

Called Methods

No outgoing method calls

assertDoMoveIsOk

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

protected void assertDoMoveIsOk(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.doMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals(MoveStatus.MOVE_OK, ms);
}

putTrainAtStationWaiting4FullLoad

Class: jfreerails.controller.MoveTrainPreMove2ndTest

Documentation

No documentation available

Source Code

private void putTrainAtStationWaiting4FullLoad() {
// Set wait until full on schedule.
ImInts newConsist = new ImInts(0, 0);
TrainOrdersModel order0 = new TrainOrdersModel(2, newConsist, true, false);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
MutableSchedule schedule = new MutableSchedule(ta.getSchedule());
schedule.setOrder(0, order0);
ImmutableSchedule imSchedule = schedule.toImmutableSchedule();
world.set(principal, KEY.TRAIN_SCHEDULES, 0, imSchedule);
assertEquals(0, ta.getSchedule().getOrderToGoto());
assertTrue(ta.getSchedule().getOrder(0).waitUntilFull);
// Add some cargo to station #2, but not enough to fill the train.
addCargoAtStation(2, 20);
// Move the train to just before station 2.
PositionOnTrack pot;
TrainMotion tm;
do {
tm = moveTrain();
pot = tm.getFinalPosition();
} while (pot.getX() < station2Location.x);
assertEquals(station2Location.x, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
// The train should now stop at the station
// and wait for a full load.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station2Location.y, pot.getY());
assertEquals(WAITING_FOR_FULL_LOAD, tm.getActivity());
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
assertFalse("The train isn't full and there is no cargo to add, so we should be able to generate a move.", preMove.isUpdateDue(world));
}

TrainScheduleJPanel

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

public TrainScheduleJPanel() {
initComponents();
}

readFromClient

Class: jfreerails.network.InetConnection2Client

Documentation

No documentation available

Source Code

public FreerailsSerializable[] readFromClient() throws IOException {
return read();
}

moveFailed

Class: jfreerails.move.MoveStatus

Documentation

No documentation available

Source Code

public static MoveStatus moveFailed(String reason) {
return new MoveStatus(false, reason);
}

Called Methods

No outgoing method calls

actionPerformed

Class: jfreerails.client.view.Unknown

Documentation

No documentation available

Source Code

public void actionPerformed(ActionEvent arg0) {
closeContent();
}

equals

Class: jfreerails.world.top.ActivityAndTime

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ActivityAndTime))
return false;
final ActivityAndTime activityAndTime = (ActivityAndTime) o;
if (!act.equals(activityAndTime.act))
return false;
if (startTime != activityAndTime.startTime)
return false;
return true;
}

Called Methods

No outgoing method calls

removeCloseButton

Class: jfreerails.client.view.StationInfoJPanel

Documentation

No documentation available

Source Code

void removeCloseButton() {
this.remove(close);
}

Called Methods

No outgoing method calls

formKeyPressed

Class: experimental.DialogueBoxTester

Documentation

No documentation available

Source Code

private void formKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_formKeyPressed
if (java.awt.event.KeyEvent.VK_ESCAPE == evt.getKeyCode()) {
dialogueBoxController.closeContent();
}
}// GEN-LAST:event_formKeyPressed

shutdownOutput

Class: jfreerails.network.AbstractInetConnection

Documentation

No documentation available

Source Code

private synchronized void shutdownOutput() throws IOException {
if (!status.isOpen()) {
throw new IllegalStateException();
}
status.close();
inetConnection.shutdownOutput();
logger.fine(this + "Shut down output.");
}

testTrackPieceIsLegal

Class: jfreerails.world.track.LegalTrackConfigurationsTest

Documentation

No documentation available

Source Code

public void testTrackPieceIsLegal() {
ArrayList<String> templates = new ArrayList<String>();
templates.add("000111000");
LegalTrackConfigurations ltc = new LegalTrackConfigurations(-1,
templates);
TrackConfiguration template = TrackConfiguration
.getFlatInstance("010010010");
assertEquals(true, ltc.trackConfigurationIsLegal(template));
template = TrackConfiguration.getFlatInstance("010111000");
assertEquals(false, ltc.trackConfigurationIsLegal(template));
}

testPathFinding

Class: jfreerails.controller.MoveTrainPreMove2ndTest

Documentation

No documentation available

Source Code

public void testPathFinding() {
// setTargetAsStation2();
Step step = nextStep();
assertEquals(EAST, step);
moveTrain();
assertEquals(EAST, nextStep());
moveTrain();
assertEquals(EAST, nextStep());
}

validateT

Class: jfreerails.world.train.ConstAcc

Documentation

No documentation available

Source Code

private void validateT(double t){
if(t < 0 || t > finalT)
throw new IllegalArgumentException("("+t+" < 0 || "+t+" > "+finalT+")");
}

Called Methods

No outgoing method calls

removeLastJMenuItemActionPerformed

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void removeLastJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_removeLastJMenuItemActionPerformed
removeLastWagon();
}// GEN-LAST:event_removeLastJMenuItemActionPerformed

ChangeTileMove

Class: jfreerails.move.ChangeTileMove

Documentation

No documentation available

Source Code

public ChangeTileMove(ReadOnlyWorld w, Point p, int terrainTypeAfter) {
this.x = p.x;
this.y = p.y;
this.before = (FreerailsTile) w.getTile(x, y);
this.after = FreerailsTile.getInstance(terrainTypeAfter, before
.getTrackPiece());
}

write

Class: jfreerails.util.Utils

Documentation

/** Used when debugging. */

Source Code

/** Used when debugging. */
public static void write(Serializable m, String fileName) {
try {
File f = new File(fileName);
OutputStream out = new FileOutputStream(f);
ObjectOutputStream objectOut = new ObjectOutputStream(out);
objectOut.writeObject(m);
objectOut.flush();
objectOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Called Methods

No outgoing method calls

size

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

/**
* Returns the number of elements in the specified list.
*/

Source Code

/**
* Returns the number of elements in the specified list.
*/
int size(SKEY key);

Called Methods

No outgoing method calls

sanityCheck

Class: jfreerails.world.train.TrainMotion

Documentation

/** Checks we are not creating an object with an inconsistent state. That is, at the
* time stored in the field duration, the engine must not have gone off the end of the path.*/

Source Code

/** Checks we are not creating an object with an inconsistent state. That is, at the
* time stored in the field duration, the engine must not have gone off the end of the path.*/
private void sanityCheck() {
double offset = calcOffSet(duration);
double totalLength = path.getTotalDistance();
double trainLengthDouble = trainLength;
if(totalLength < offset + trainLengthDouble)
throw new IllegalStateException(offset +" + "+ trainLengthDouble+" > " +totalLength);
}

add

Class: jfreerails.util.List1DDiff

Documentation

No documentation available

Source Code

public int add(T element) {
return super.addElement(element);
}

moveForward

Class: jfreerails.controller.GraphExplorer

Documentation

/**
* Moves this GraphExplorer from the current vertex to the vertex that is
* connected to the current vertex by the current edge.
*/

Source Code

/**
* Moves this GraphExplorer from the current vertex to the vertex that is
* connected to the current vertex by the current edge.
*/
void moveForward();

Called Methods

No outgoing method calls

FreerailsGameServer

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public FreerailsGameServer(SavedGamesManager gamesManager) {
this.savedGamesManager = gamesManager;
}

Called Methods

No outgoing method calls

execute

Class: jfreerails.network.specifics.LoadGameMessage2Server

Documentation

No documentation available

Source Code

public MessageStatus execute(ServerControlInterface server) {
try {
server.loadgame(filename);
return new MessageStatus(id, true);
} catch (Exception e) {
e.printStackTrace();
return new MessageStatus(id, false, e.getMessage());
}
}

trackConfigurationIsLegal

Class: jfreerails.world.track.LegalTrackConfigurations

Documentation

No documentation available

Source Code

public boolean trackConfigurationIsLegal(
TrackConfiguration trackConfiguration) {
return legalConfigs.contains(trackConfiguration);
}

getStepIndex

Class: jfreerails.world.train.PathOnTiles

Documentation

/**
* Returns the index of the step that takes the distance travelled over the
* specified distance.
*
* @throws IllegalArgumentException
* if distance < 0
* @throws IllegalArgumentException
* if distance > getLength()
*/

Source Code

/**
* Returns the index of the step that takes the distance travelled over the
* specified distance.
*
* @throws IllegalArgumentException
* if distance < 0
* @throws IllegalArgumentException
* if distance > getLength()
*/
public int getStepIndex(int distance) {
if (0 > distance)
throw new IllegalArgumentException("distance < 0");
int distanceSoFar = 0;
for (int i = 0; i < vectors.size(); i++) {
Step v = vectors.get(i);
distanceSoFar += v.getLength();
if (distanceSoFar >= distance)
return i;
}
throw new IllegalArgumentException("distance > getLength()");
}

actionPerformed

Class: jfreerails.client.view.LoadGameAction

Documentation

No documentation available

Source Code

public void actionPerformed(ActionEvent e) {
dbc.showSelectSavedGame2Load();
/*
ImStringList files = (ImStringList)modelRoot.getProperty(Property.SAVED_GAMES_LIST);
Object[] saves = new Object[files.size()];
for (int i = 0; i < files.size(); i++) {
saves[i] = files.get(i);
}
// Display a JOptionPane that lists the existing saved games
try {
Object showInputDialog = JOptionPane.showInputDialog(null,
"Saved Games:", "Select game to load",
JOptionPane.INFORMATION_MESSAGE, null, saves, saves[0]);
String filename = showInputDialog.toString();
// Load the game chosen
Message2Server message2 = new LoadGameMessage2Server(1,
filename);
modelRoot.sendCommand(message2);
} catch (Exception exept) {
// <Hack>
// When no saved game is selected, or one that doesnt exist,
// nothing changes
// </.Hack>
}
*/
}

selectTileIcon

Class: jfreerails.client.renderer.SpecialTileRenderer

Documentation

No documentation available

Source Code

@Override
public int selectTileIcon(int x, int y, ReadOnlyWorld w) {
return 0;
}

Called Methods

No outgoing method calls

SKEY

Class: jfreerails.world.top.SKEY

Documentation

No documentation available

Source Code

private SKEY() {
this.keyNumber = numberOfKeys;
keys[keyNumber] = this;
numberOfKeys++;
}

Called Methods

No outgoing method calls

tryUndoMove

Class: jfreerails.move.UndoMove

Documentation

No documentation available

Source Code

public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
return move2undo.tryDoMove(w, p);
}

tryDoMove

Class: jfreerails.move.UndoMove

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
return move2undo.tryUndoMove(w, p);
}

incrementSupplyAndDemand

Class: jfreerails.controller.CalcCargoSupplyRateAtStation

Documentation

No documentation available

Source Code

private void incrementSupplyAndDemand(int i, int j) {
int tileTypeNumber = ((FreerailsTile) w.getTile(i, j))
.getTerrainTypeID();
TerrainType terrainType = (TerrainType) w.get(SKEY.TERRAIN_TYPES,
tileTypeNumber);
// Calculate supply.
ImList<Production> production = terrainType.getProduction();
// loop through the production array and increment
// the supply rates for the station
for (int m = 0; m < production.size(); m++) {
int type = production.get(m).getCargoType();
int rate = production.get(m).getRate();
// loop through supplies vector and increment the cargo values as
// required
updateSupplyRate(type, rate);
}
// Now calculate demand.
ImList<Consumption> consumption = terrainType.getConsumption();
for (int m = 0; m < consumption.size(); m++) {
int type = consumption.get(m).getCargoType();
int prerequisite = consumption.get(m).getPrerequisite();
// The prerequisite is the number tiles of this type that must
// be within the station radius before the station demands the
// cargo.
demand[type] += PREREQUISITE_FOR_DEMAND / prerequisite;
}
ImList<Conversion> conversion = terrainType.getConversion();
for (int m = 0; m < conversion.size(); m++) {
int type = conversion.get(m).getInput();
// Only one tile that converts the cargo type is needed for the
// station to demand the cargo type.
demand[type] += PREREQUISITE_FOR_DEMAND;
converts[type] = conversion.get(m).getOutput();
}
}

getPreferredSize

Class: jfreerails.client.view.OverviewMapJComponent

Documentation

No documentation available

Source Code

@Override
public Dimension getPreferredSize() {
return mapView.getMapSizeInPixels();
}

AbstractMoveTestCase

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

public AbstractMoveTestCase(String str) {
super(str);
}

Called Methods

No outgoing method calls

getPrincipal

Class: jfreerails.move.AddTransactionMove

Documentation

No documentation available

Source Code

public FreerailsPrincipal getPrincipal() {
return principal;
}

Called Methods

No outgoing method calls

countOpenConnections

Class: jfreerails.network.EchoGameServer

Documentation

No documentation available

Source Code

public synchronized int countOpenConnections() {
Iterator<Connection2Client> it = connections.iterator();
while (it.hasNext()) {
Connection2Client connection = it.next();
if (!connection.isOpen()) {
it.remove();
}
}
return connections.size();
}

nextEdge

Class: jfreerails.controller.GraphExplorer

Documentation

/**
* Sets the current edge to the current vertex's next edge. Throws a
* NoSuchElementException if the vertex does not have another edge.
*/

Source Code

/**
* Sets the current edge to the current vertex's next edge. Throws a
* NoSuchElementException if the vertex does not have another edge.
*/
void nextEdge();

Called Methods

No outgoing method calls

nextStep

Class: jfreerails.util.FreerailsProgressMonitor

Documentation

No documentation available

Source Code

void nextStep(int max);

Called Methods

No outgoing method calls

getID

Class: jfreerails.network.specifics.SaveGameMessage2Server

Documentation

No documentation available

Source Code

public int getID() {
return id;
}

Called Methods

No outgoing method calls

testMove

Class: jfreerails.move.ChangeTrackPieceCompositeMoveTest

Documentation

No documentation available

Source Code

@Override
public void testMove() {
ImPoint pointA = new ImPoint(0, 0);
TrackRule trackRule = (TrackRule) getWorld().get(SKEY.TRACK_RULES, 0);
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(pointA, southeast, trackRule,
trackRule, getWorld(), MapFixtureFactory.TEST_PRINCIPAL);
assertSurvivesSerialisation(move);
assertOkButNotRepeatable(move);
setUp();
assertDoThenUndoLeavesWorldUnchanged(move);
}

newBlankImage

Class: jfreerails.client.common.ImageManager

Documentation

No documentation available

Source Code

Image newBlankImage(int height, int width);

Called Methods

No outgoing method calls

getStockInThisRRs

Class: jfreerails.controller.FinancialDataGatherer

Documentation

No documentation available

Source Code

public int[] getStockInThisRRs() {
if(null == stockInThisRRs){
stockInThisRRs = new int[w.getNumberOfPlayers()];
for(int i = 0; i < w.getNumberOfPlayers(); i++){
Player p = w.getPlayer(i);
FinancialDataGatherer temp = new FinancialDataGatherer(w, p.getPrincipal());
stockInThisRRs[i] = temp.stockInRRs[this.playerID];
}
}
return stockInThisRRs;
}

getUpdatedTiles

Class: jfreerails.move.UpgradeTrackMove

Documentation

No documentation available

Source Code

public Rectangle getUpdatedTiles() {
ChangeTrackPieceMove m = (ChangeTrackPieceMove) this.getMove(0);
return m.getUpdatedTiles();
}

ServerControlModel

Class: jfreerails.client.view.ServerControlModel

Documentation

No documentation available

Source Code

public ServerControlModel(ModelRootImpl mr) {
this.modelRoot = mr;
mr.addPropertyChangeListener(this);
setServerControlInterface();
}

setWorld

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

void setWorld(World world) {
this.world = world;
}

Called Methods

No outgoing method calls

getFinishTime

Class: jfreerails.world.top.ActivityIteratorImpl

Documentation

No documentation available

Source Code

public double getFinishTime() {
double ticks = ant.startTime + ant.act.duration();
return ticks;
}

changeStake

Class: jfreerails.controller.FinancialDataGatherer

Documentation

No documentation available

Source Code

public void changeStake(int stakeHolder, int deltaStock) {
}

Called Methods

No outgoing method calls

setImage

Class: jfreerails.client.common.ImageManager

Documentation

No documentation available

Source Code

void setImage(String relativeFilename, Image i);

Called Methods

No outgoing method calls

createReportsMenu

Class: jfreerails.client.top.GUIComponentFactory

Documentation

No documentation available

Source Code

JMenu createReportsMenu();

Called Methods

No outgoing method calls

ActionAdapter

Class: jfreerails.client.common.ActionAdapter

Documentation

/**
* @param actions
* An array of the actions to be used. The ComboBoxModel objects
* are taken from the NAME property of the Action. The
* ButtonModel icons are obtained from the SMALL_ICON property.
* @param selected
* Index of the default selected action.
*/

Source Code

/**
* @param actions
* An array of the actions to be used. The ComboBoxModel objects
* are taken from the NAME property of the Action. The
* ButtonModel icons are obtained from the SMALL_ICON property.
* @param selected
* Index of the default selected action.
*/
public ActionAdapter(Action[] actions, int selected) {
this(actions);
for (int i = 0; i < buttonModels.size(); i++) {
MappedButtonModel bm = buttonModels.get(i);
bm.setSelected(i == selected);
}
}

Called Methods

compareTo

Class: jfreerails.controller.OpenListEntry

Documentation

No documentation available

Source Code

public int compareTo(OpenListEntry o) {
// XXX Work around for JDK Bug ID: 6207984
if (f == o.f) {
return node - o.node;
}
return f - o.f;
}

Called Methods

No outgoing method calls

testRefreshBeforeBufferIsSet

Class: jfreerails.client.renderer.SquareTileBackgroundRendererTest

Documentation

/** Testcase to reproduce bug [ 1303162 ] Unexpected Exception:*/

Source Code

/** Testcase to reproduce bug [ 1303162 ] Unexpected Exception:*/
public void testRefreshBeforeBufferIsSet(){
SquareTileBackgroundRenderer stbr = new SquareTileBackgroundRenderer(renderer);
stbr.refreshAll();
stbr.refreshTile(1, 2);
}

initComponents

Class: jfreerails.client.view.ConfirmExitJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jPanel2 = new javax.swing.JPanel();
confirmExit = new javax.swing.JButton();
closeJButton = new javax.swing.JButton();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(240, 140));
jLabel1.setText("Are you sure you want to Exit?");
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
jPanel1.add(jLabel1);
add(jPanel1, new java.awt.GridBagConstraints());
jPanel2.setLayout(new java.awt.GridBagLayout());
confirmExit.setText("Exit");
confirmExit.setContentAreaFilled(false);
confirmExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
confirmExitActionPerformed(evt);
}
});
jPanel2.add(confirmExit, new java.awt.GridBagConstraints());
closeJButton.setText("Cancel");
jPanel2.add(closeJButton, new java.awt.GridBagConstraints());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.ipadx = 15;
gridBagConstraints.insets = new java.awt.Insets(3, 0, 0, 0);
add(jPanel2, gridBagConstraints);
}// GEN-END:initComponents

getMapWidth

Class: jfreerails.world.top.WorldDiffs

Documentation

No documentation available

Source Code

@Override
public int getMapWidth() {
return underlying.getMapWidth();
}

equalsBySerialization

Class: jfreerails.util.Utils

Documentation

No documentation available

Source Code

public static boolean equalsBySerialization(Serializable a, Serializable b) {
byte[] bytesA = write2ByteArray(a);
byte[] bytesB = write2ByteArray(b);
if (bytesA.length != bytesB.length)
return false;
for (int i = 0; i < bytesA.length; i++) {
if (bytesA[i] != bytesB[i])
return false;
}
return true;
}

startPrefixMapping

Class: jfreerails.server.parser.Track_TilesParser

Documentation

No documentation available

Source Code

public void startPrefixMapping(final java.lang.String prefix,
final java.lang.String uri) throws SAXException {
}

Called Methods

No outgoing method calls

hasNext

Class: jfreerails.controller.RandomPathFinder

Documentation

No documentation available

Source Code

public boolean hasNext() {
return trackExplorer.hasNextEdge();
}

ClassLocater

Class: jfreerails.util.ClassLocater

Documentation

/**
* Automatically adds sun's classes, the java library classes, and the
* Apache log4j classes (a lib used by ClassLocater!) to the skip list; it's
* very unlikely that you're trying to locate any of these!
*/

Source Code

/**
* Automatically adds sun's classes, the java library classes, and the
* Apache log4j classes (a lib used by ClassLocater!) to the skip list; it's
* very unlikely that you're trying to locate any of these!
*/
public ClassLocater() {
addSkipPrefix("org.apache.log4j.");
addSkipPrefix("com.sun.");
addSkipPrefix("java");
addSkipPrefix("junit");
}

setProperty

Class: jfreerails.launcher.Launcher

Documentation

No documentation available

Source Code

public void setProperty(String key, String value){
props.setProperty(key, value);
}

Called Methods

No outgoing method calls

TrainOrderJPanel

Class: jfreerails.client.view.TrainOrderJPanel

Documentation

No documentation available

Source Code

public TrainOrderJPanel() {
initComponents();
this.setBackground(backgroundColor);
}

stopTrain

Class: jfreerails.controller.MoveTrainPreMove

Documentation

No documentation available

Source Code

public Move stopTrain(ReadOnlyWorld w) {
TrainMotion motion = lastMotion(w);
SpeedAgainstTime stopped = ConstAcc.STOPPED;
double duration = motion.duration();
int trainLength = motion.getTrainLength();
PathOnTiles tiles = motion.getTiles(duration);
int engineDist = tiles.steps();
TrainMotion nextMotion = new TrainMotion(tiles, engineDist,
trainLength, stopped);
return new NextActivityMove(nextMotion, trainID, principal);
}

apply

Class: jfreerails.controller.ScreenHandler

Documentation

No documentation available

Source Code

public synchronized void apply() {
switch (mode) {
case FULL_SCREEN: {
goFullScreen(frame, displayMode);
break;
}
case WINDOWED_MODE: {
// Some of the dialogue boxes do not get layed out properly if they
// are smaller than their
// minimum size. JFrameMinimumSizeEnforcer increases the size of the
// Jframe when its size falls
// below the specified size.
frame.addComponentListener(new JFrameMinimumSizeEnforcer(640, 480));
frame.setSize(640, 480);
frame.setVisible(true);
break;
}
case FIXED_SIZE_WINDOWED_MODE: {
/*
* We need to make the frame not displayable before calling
* setUndecorated(true) otherwise a
* java.awt.IllegalComponentStateException will get thrown.
*/
if (frame.isDisplayable()) {
frame.dispose();
}
frame.setUndecorated(true);
frame.setResizable(false);
frame.setSize(640, 480);
frame.setVisible(true);
break;
}
default:
throw new IllegalArgumentException(String.valueOf(mode));
}
createBufferStrategy();
frame.addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(java.awt.event.ComponentEvent evt) {
createBufferStrategy();
}
});
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowIconified(WindowEvent e) {
isMinimised = true;
}
@Override
public void windowDeiconified(WindowEvent e) {
isMinimised = false;
}
});
isInUse = true;
}

getThreadName

Class: jfreerails.network.AbstractInetConnection

Documentation

No documentation available

Source Code

abstract String getThreadName();

Called Methods

No outgoing method calls

getImage

Class: jfreerails.client.renderer.MyRenderersRoot

Documentation

No documentation available

Source Code

@Override
public Image getImage(String relativeFilename) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}

Called Methods

No outgoing method calls

get

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public FreerailsSerializable get(SKEY key, int index) {
return sharedLists.get(key.getKeyID(), index);
}

getEngineTypeName

Class: jfreerails.world.train.EngineType

Documentation

No documentation available

Source Code

public String getEngineTypeName() {
return engineTypeName;
}

Called Methods

No outgoing method calls

hideAllMessages

Class: jfreerails.launcher.LauncherInterface

Documentation

No documentation available

Source Code

void hideAllMessages();

Called Methods

No outgoing method calls

testEquals

Class: jfreerails.world.common.ImIntsTest

Documentation

No documentation available

Source Code

public void testEquals(){
int[] a = { 1, 2, 3 };
int[] b = { 1, 2, 3 };
ImInts ai = new ImInts(a);
ImInts bi = new ImInts(b);
assertEquals(ai, bi);
ImInts ci = new ImInts(1, 2, 3 );
assertEquals(ai, ci);
}

Called Methods

No outgoing method calls

PathOnTiles

Class: jfreerails.world.train.PathOnTiles

Documentation

/**
* @throws NullPointerException
* if null == start
* @throws NullPointerException
* if null == vectors
* @throws NullPointerException
* if null == vectors[i] for any i;
*/

Source Code

/**
* @throws NullPointerException
* if null == start
* @throws NullPointerException
* if null == vectors
* @throws NullPointerException
* if null == vectors[i] for any i;
*/
public PathOnTiles(ImPoint start, Step... vectors) {
if (null == start)
throw new NullPointerException();
this.vectors = new ImList<Step>(vectors);
this.vectors.checkForNulls();
this.start = start;
}

clear

Class: jfreerails.util.ArrayBase

Documentation

/**
* Set the array to the empty state.
*/

Source Code

/**
* Set the array to the empty state.
*/
public final void clear() {
setSize(0);
}

end_Tiles

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* A container element end event handling method.
*/

Source Code

/**
* A container element end event handling method.
*/
void end_Tiles() throws SAXException;

Called Methods

No outgoing method calls

getWorldIndex

Class: jfreerails.world.player.FreerailsPrincipal

Documentation

/**
* returns -1 if it's not a player
* @return the index in the world structures
*/

Source Code

/**
* returns -1 if it's not a player
* @return the index in the world structures
*/
public int getWorldIndex() {
return worldIndex;
}

Called Methods

No outgoing method calls

getYear

Class: jfreerails.world.common.GameCalendar

Documentation

No documentation available

Source Code

public int getYear(int ticks) {
return startYear + (ticks / ticksPerYear);
}

Called Methods

No outgoing method calls

getImageManager

Class: jfreerails.client.top.RenderersRootImpl

Documentation

No documentation available

Source Code

public ImageManager getImageManager() {
return imageManager;
}

Called Methods

No outgoing method calls

buyOrSellStock

Class: jfreerails.world.accounts.StockTransaction

Documentation

No documentation available

Source Code

public static StockTransaction buyOrSellStock(int playerId, int quantity,
Money stockPrice) {
// Buys another Players Stock, Uses another Category
Money value = new Money(stockPrice.getAmount() * quantity * -1);
return new StockTransaction(Transaction.Category.TRANSFER_STOCK,
playerId, quantity, value);
}

getSetTargetTickPerSecondActions

Class: jfreerails.client.view.ServerControlModel

Documentation

/**
* @return an action adapter to set the target ticks per second
*/

Source Code

/**
* @return an action adapter to set the target ticks per second
*/
public ActionAdapter getSetTargetTickPerSecondActions() {
return targetTicksPerSecondActions;
}

Called Methods

No outgoing method calls

priorityOrdersJButtonActionPerformed

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void priorityOrdersJButtonActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_priorityOrdersJButtonActionPerformed
MutableSchedule s = getSchedule();
try {
s.setPriorityOrders(new TrainOrdersModel(getFirstStationID(), null,
false, false));// TODO fix bug
showSelectStation(s, Schedule.PRIORITY_ORDERS);
} catch (NoSuchElementException e) {
logger
.warning("No stations exist so can't add station to schedule!");
}
}// GEN-LAST:event_priorityOrdersJButtonActionPerformed

send2All

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

private void send2All(FreerailsSerializable message) {
send2AllExcept(null, message);
}

string2RGBValue

Class: jfreerails.server.parser.CargoAndTerrainHandlerImpl

Documentation

No documentation available

Source Code

private int string2RGBValue(String temp_number) {
int rgb = Integer.parseInt(temp_number, 16);
/*
* We need to change the format of the rgb value to the same one as used
* by the the BufferedImage that stores the map. See
* jfreerails.common.Map
*/
rgb = new java.awt.Color(rgb).getRGB();
return rgb;
}

Called Methods

No outgoing method calls

testIsValid

Class: jfreerails.client.common.ImageManagerImplTest

Documentation

No documentation available

Source Code

public void testIsValid() {
assertTrue(ImageManagerImpl.isValid("cursor/infomode.png"));
assertFalse(ImageManagerImpl.isValid("/cursor/infomode.png"));
}

createDateJLabel

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

public JLabel createDateJLabel() {
return datejLabel;
}

Called Methods

No outgoing method calls

trackPieceIsLegal

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

public boolean trackPieceIsLegal(TrackConfiguration config) {
return testTrackPieceLegality(config.getTrackGraphicsID());
}

UnexpectedExceptionForm

Class: jfreerails.controller.UnexpectedExceptionForm

Documentation

/** Creates new form UnexpectedExceptionForm */

Source Code

/** Creates new form UnexpectedExceptionForm */
public UnexpectedExceptionForm() {
initComponents();
}

startPrefixMapping

Class: jfreerails.server.parser.CargoAndTerrainParser

Documentation

/**
* This SAX interface method is implemented by the parser.
*
*/

Source Code

/**
* This SAX interface method is implemented by the parser.
*
*/
public final void startPrefixMapping(final java.lang.String prefix,
final java.lang.String uri) throws SAXException {
}

Called Methods

No outgoing method calls

getStart

Class: jfreerails.world.train.PathOnTiles

Documentation

No documentation available

Source Code

public ImPoint getStart() {
return start;
}

Called Methods

No outgoing method calls

DeliverCargoReceipt

Class: jfreerails.world.accounts.DeliverCargoReceipt

Documentation

No documentation available

Source Code

public DeliverCargoReceipt(Money m, int quantity, int stationId,
CargoBatch cb, int trainId) {
super(m, Category.CARGO_DELIVERY);
this.stationId = stationId;
this.quantity = quantity;
this.cb = cb;
this.trainId = trainId;
}

setWorldDiffs

Class: jfreerails.client.renderer.BuildTrackController

Documentation

No documentation available

Source Code

private void setWorldDiffs(WorldDiffs worldDiffs) {
modelRoot.setProperty(ModelRoot.Property.PROPOSED_TRACK, worldDiffs);
}

show

Class: jfreerails.client.renderer.BuildTrackController

Documentation

No documentation available

Source Code

public void show() {
this.setVisible(true);
}

TestActivity

Class: jfreerails.world.top.TestActivity

Documentation

No documentation available

Source Code

public TestActivity(int duration) {
this.duration = duration;
}

Called Methods

No outgoing method calls

testCityModel

Class: jfreerails.world.terrain.MiscTest

Documentation

No documentation available

Source Code

public void testCityModel() {
CityModel cm1 = new CityModel("London", 20, 70);
CityModel cm2 = new CityModel("Cardiff", 20, 70);
testHashCodeAndEquals(cm1);
testHashCodeAndEquals(cm2);
assertDifferent(cm1, cm2);
}

cancelStationPlacement

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

No documentation available

Source Code

private void cancelStationPlacement() {
// Cancel build station mode..
stationBuildModel.getStationCancelAction().actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""));
}

testNonSharedLists

Class: jfreerails.world.top.WorldDiffsTest

Documentation

No documentation available

Source Code

public void testNonSharedLists() {
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
StationModel station0 = new StationModel();
underlyingWorld.add(player0.getPrincipal(), KEY.STATIONS, station0);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(0, worldDiff.listDiffs());
// First, for an existing player
assertEquals(1, worldDiff.size(player0.getPrincipal(), KEY.STATIONS));
FreerailsSerializable fs = worldDiff.get(player0.getPrincipal(),
KEY.STATIONS, 0);
assertEquals(station0, fs);
// Add a station.
StationModel station1 = new StationModel();
worldDiff.add(player0.getPrincipal(), KEY.STATIONS, station1);
assertEquals(2, worldDiff.size(player0.getPrincipal(), KEY.STATIONS));
fs = worldDiff.get(player0.getPrincipal(), KEY.STATIONS, 1);
assertEquals(station1, fs);
// Change a station.
StationModel station2 = new StationModel();
worldDiff.set(player0.getPrincipal(), KEY.STATIONS, 0, station2);
fs = worldDiff.get(player0.getPrincipal(), KEY.STATIONS, 0);
assertEquals(station2, fs);
// Remove both stations.
fs = worldDiff.removeLast(player0.getPrincipal(), KEY.STATIONS);
assertEquals(station1, fs);
fs = worldDiff.removeLast(player0.getPrincipal(), KEY.STATIONS);
assertEquals(station2, fs);
assertEquals(0, worldDiff.size(player0.getPrincipal(), KEY.STATIONS));
// Add a station again.
int i = worldDiff.add(player0.getPrincipal(), KEY.STATIONS, station1);
assertEquals(0, i);
assertEquals(1, worldDiff.size(player0.getPrincipal(), KEY.STATIONS));
// Second, for a new player
worldDiff.addPlayer(player1);
assertEquals(2, worldDiff.getNumberOfPlayers());
assertEquals(player1, worldDiff.getPlayer(1));
assertEquals(0, worldDiff.size(player1.getPrincipal(), KEY.STATIONS));
worldDiff.add(player1.getPrincipal(), KEY.STATIONS, station1);
assertEquals(1, worldDiff.size(player1.getPrincipal(), KEY.STATIONS));
worldDiff.set(player1.getPrincipal(), KEY.STATIONS, 0, station2);
worldDiff.add(player1.getPrincipal(), KEY.STATIONS, station1);
}

findNearestStation

Class: jfreerails.client.view.NearestStationFinder

Documentation

No documentation available

Source Code

public int findNearestStation(int x, int y) {
// Find nearest station.
int distanceToClosestSquared = Integer.MAX_VALUE;
NonNullElements it = new NonNullElements(KEY.STATIONS, world, principal);
int nearestStation = NOT_FOUND;
while (it.next()) {
StationModel station = (StationModel) it.getElement();
int deltaX = x - station.x;
int deltaY = y - station.y;
int distanceSquared = deltaX * deltaX + deltaY * deltaY;
if (distanceSquared < distanceToClosestSquared
&& MAX_DISTANCE_TO_SELECT_SQUARED > distanceSquared) {
distanceToClosestSquared = distanceSquared;
nearestStation = it.getIndex();
}
}
return nearestStation;
}

updateSchedule

Class: jfreerails.controller.TrainStopsHandler

Documentation

No documentation available

Source Code

void updateSchedule() {
TrainModel train = (TrainModel) worldDiffs.get(principal, KEY.TRAINS, this.trainId);
int scheduleID = train.getScheduleID();
ImmutableSchedule currentSchedule = (ImmutableSchedule) worldDiffs.get(principal,
KEY.TRAIN_SCHEDULES, scheduleID);
MutableSchedule schedule = new MutableSchedule(currentSchedule);
StationModel station = null;
TrainOrdersModel order = schedule.getOrder(schedule.getOrderToGoto());
boolean waiting4FullLoad = order.waitUntilFull && !isTrainFull();
if (!waiting4FullLoad) {
schedule.gotoNextStation();
ImmutableSchedule newSchedule = schedule.toImmutableSchedule();
worldDiffs.set(principal, KEY.TRAIN_SCHEDULES, scheduleID, newSchedule);
int stationNumber = schedule.getStationToGoto();
station = (StationModel) worldDiffs.get(principal, KEY.STATIONS, stationNumber);
if (null == station) {
logger.warning("null == station, train " + trainId
+ " doesn't know where to go next!");
}
}
}

isPlayer

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

private boolean isPlayer(String username) {
for (NameAndPassword p : players) {
if (p.username.equals(username))
return true;
}
return false;
}

Called Methods

No outgoing method calls

numberOfScheduledStops

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

private int numberOfScheduledStops() {
return orders.size() - firstScheduleStop();
}

showDetailsActionPerformed

Class: jfreerails.client.view.TrainListJPanel

Documentation

No documentation available

Source Code

private void showDetailsActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showDetailsActionPerformed
showTrainDetails.actionPerformed(evt);
}// GEN-LAST:event_showDetailsActionPerformed

Called Methods

No outgoing method calls

nextStep

Class: jfreerails.launcher.ProgressJPanel

Documentation

No documentation available

Source Code

public void nextStep(int max) {
//So that the waiting for game to start message
//goes away.
owner.hideAllMessages();
step++;
stepSize = max;
if(numSteps < step)
throw new IllegalStateException();
}

doMove

Class: jfreerails.move.AddActiveEntityMove

Documentation

No documentation available

Source Code

public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.ok)
w.addActiveEntity(principal, activity);
return ms;
}

testMap

Class: jfreerails.server.MapFixtureFactory2Test

Documentation

No documentation available

Source Code

public void testMap() {
assertEquals(w1.getMapWidth(), 50);
assertEquals(w1.getMapWidth(), 50);
}

getMaximumConsecutivePieces

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

public int getMaximumConsecutivePieces() {
return -1;
}

Called Methods

No outgoing method calls

end_Types

Class: jfreerails.server.parser.CargoAndTerrainHandler

Documentation

/**
* A container element end event handling method.
*
*/

Source Code

/**
* A container element end event handling method.
*
*/
public void end_Types() throws SAXException;

Called Methods

No outgoing method calls

splitMove

Class: jfreerails.network.specifics.MoveChainFork

Documentation

No documentation available

Source Code

private void splitMove(Move move) {
if (move instanceof UndoMove) {
UndoMove undoneMove = (UndoMove) move;
move = undoneMove.getUndoneMove();
}
if (move instanceof CompositeMove) {
ImList<Move> moves = ((CompositeMove) move).getMoves();
for (int i = 0; i < moves.size(); i++) {
splitMove(moves.get(i));
}
} else {
for (int i = 0; i < splitMoveReceivers.size(); i++) {
MoveReceiver m = splitMoveReceivers.get(i);
m.processMove(move);
}
if (move instanceof AddItemToListMove) {
AddItemToListMove mm = (AddItemToListMove) move;
sendItemAdded(mm.getKey(), mm.getIndex(), mm.getPrincipal());
} else if (move instanceof ChangeItemInListMove) {
ChangeItemInListMove mm = (ChangeItemInListMove) move;
sendListUpdated(mm.getKey(), mm.getIndex(), mm.getPrincipal());
} else if (move instanceof RemoveItemFromListMove) {
RemoveItemFromListMove mm = (RemoveItemFromListMove) move;
sendItemRemoved(mm.getKey(), mm.getIndex(), mm.getPrincipal());
} else if (move instanceof MapUpdateMove) {
Rectangle r = ((MapUpdateMove) move).getUpdatedTiles();
sendMapUpdated(r);
} else if (move instanceof TimeTickMove) {
long currentTime = System.currentTimeMillis();
lastTickTime = currentTime;
}
}
}

test2

Class: jfreerails.controller.BuildTrackExplorerTest

Documentation

/** Test when we cannot build on some terrain types. */

Source Code

/** Test when we cannot build on some terrain types. */
public void test2() {
// Check the the Ocean type is where we think it is.
int oceanTypeNumber = 4;
TileTypeImpl ocean = (TileTypeImpl) world.get(SKEY.TERRAIN_TYPES,
oceanTypeNumber);
assertEquals(TerrainType.Category.Ocean, ocean.getCategory());
// Check that track cannot be built on ocean.
for (int i = 0; i < world.size(SKEY.TRACK_RULES); i++) {
TrackRule rule = (TrackRule) world.get(SKEY.TRACK_RULES, i);
assertFalse(rule.canBuildOnThisTerrainType(ocean.getCategory()));
}
// Place some ocean.
FreerailsTile tile = FreerailsTile.getInstance(oceanTypeNumber);
world.setTile(10, 9, tile);
world.setTile(11, 10, tile);
PositionOnTrack start;
// Test starting in the middle of the map.
start = PositionOnTrack.createComingFrom(10, 10, Step.NORTH);
BuildTrackExplorer explorer = new BuildTrackExplorer(world, principal);
explorer.setPosition(start.toInt());
assertNextVertexIs(Step.NORTH_EAST, 11, 9, explorer);
// We miss out SW, S, and SE since we don't want to double back on
// ourselves.
assertNextVertexIs(Step.WEST, 9, 10, explorer);
assertNextVertexIs(Step.NORTH_WEST, 9, 9, explorer);
assertFalse(explorer.hasNextEdge());
}

retireTrain

Class: jfreerails.server.TrainUpdater

Documentation

No documentation available

Source Code

private void retireTrain(ReadOnlyWorld world, FreerailsPrincipal principal, int trainId) {
Move m = RemoveTrainMove.getInstance(trainId, principal, world);
moveReceiver.processMove(m);
}

getLocation

Class: jfreerails.move.ChangeTrackPieceMove

Documentation

No documentation available

Source Code

public ImPoint getLocation() {
return location;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.track.LegalTrackPlacement

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return (placementRule != null ? placementRule.hashCode() : 0);
}

Called Methods

No outgoing method calls

testGetLength

Class: jfreerails.world.train.PathOnTilesTest

Documentation

No documentation available

Source Code

public void testGetLength() {
ImPoint start = new ImPoint();
Step[] vectors = new Step[] { EAST, EAST, EAST };
PathOnTiles path = new PathOnTiles(start, vectors);
assertEquals(3 * Step.TILE_DIAMETER, path.getTotalDistance(), 0.001);
}

size

Class: jfreerails.util.ArrayBase

Documentation

/**
* Get the number of values currently present in the array.
*
* @return count of values present
*/

Source Code

/**
* Get the number of values currently present in the array.
*
* @return count of values present
*/
public final int size() {
return countPresent;
}

Called Methods

No outgoing method calls

setTrackBuilderMode

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

No documentation available

Source Code

private void setTrackBuilderMode(TrackMoveProducer.BuildMode mode) {
trackMoveProducer.setTrackBuilderMode(mode);
modelRoot.setProperty(ModelRoot.Property.TRACK_BUILDER_MODE, mode);
}

setTimes

Class: jfreerails.world.top.TransactionAggregator

Documentation

No documentation available

Source Code

public void setTimes(GameTime[] times) {
if (1 > times.length) {
throw new IllegalArgumentException(
"There must be at least two values.");
}
timeValues = new GameTime[times.length];
timeValues[0] = times[0]; // since we start counting at 1.
for (int i = 1; i < times.length; i++) {
if (times[i].getTicks() < times[i - 1].getTicks()) {
throw new IllegalArgumentException("Time at index " + (i - 1)
+ " > time at index " + i + ".");
}
timeValues[i] = times[i];
}
}

testMove2

Class: jfreerails.move.NextActivityMoveTest

Documentation

No documentation available

Source Code

public void testMove2() {
World w = getWorld();
FreerailsPrincipal principal = getPrincipal();
Activity act = new WorldImplTest.TestActivity(50);
w.addActiveEntity(principal, act);
Activity act2 = new WorldImplTest.TestActivity(60);
Move move = new NextActivityMove(act2, 0,
principal);
assertDoThenUndoLeavesWorldUnchanged(move);
}

compositeTest

Class: jfreerails.move.CompositeMove

Documentation

/**
* Subclasses may override this method to perform tests which pass or fail
* depending on the combination of moves making up this composite move.
*/

Source Code

/**
* Subclasses may override this method to perform tests which pass or fail
* depending on the combination of moves making up this composite move.
*/
MoveStatus compositeTest(World w, FreerailsPrincipal p) {
return MoveStatus.MOVE_OK;
}

Called Methods

No outgoing method calls

testConnecting

Class: jfreerails.network.InetConnectionTest

Documentation

No documentation available

Source Code

public void testConnecting() {
try {
assertEquals(0, echoGameServer.countOpenConnections());
InetConnection connection = new InetConnection(ipAddress, server
.getLocalPort());
connection.open();
assertEquals(1, echoGameServer.countOpenConnections());
InetConnection connection2 = new InetConnection(ipAddress, server
.getLocalPort());
connection2.open();
assertEquals(2, echoGameServer.countOpenConnections());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}

equals

Class: jfreerails.world.common.ImPoint

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImPoint))
return false;
final ImPoint imPoint = (ImPoint) o;
if (x != imPoint.x)
return false;
if (y != imPoint.y)
return false;
return true;
}

Called Methods

No outgoing method calls

isOk

Class: jfreerails.move.MoveStatus

Documentation

No documentation available

Source Code

public boolean isOk() {
return ok;
}

Called Methods

No outgoing method calls

isOpen

Class: jfreerails.network.LocalConnection

Documentation

No documentation available

Source Code

public boolean isOpen() {
return status.isOpen();
}

uat

Class: jfreerails.world.train.ConstAcc

Documentation

No documentation available

Source Code

public static ConstAcc uat(double u, double a, double t) {
double s = u * t + a * t * t / 2;
return new ConstAcc(a, t, u, s);
}

Called Methods

No outgoing method calls

testSize

Class: jfreerails.controller.OpenListTest

Documentation

No documentation available

Source Code

public void testSize() {
OpenList openList = new OpenList();
assertEquals(0, openList.size());
openList.add(0, 4);
assertEquals(1, openList.size());
openList.popNodeWithSmallestF();
assertEquals(0, openList.size());
}

hasNextEdge

Class: jfreerails.controller.GraphExplorer

Documentation

No documentation available

Source Code

boolean hasNextEdge();

Called Methods

No outgoing method calls

start_Tile

Class: jfreerails.server.parser.CargoAndTerrainHandlerImpl

Documentation

No documentation available

Source Code

public void start_Tile(final Attributes meta) throws SAXException {
typeConsumes.clear();
typeProduces.clear();
typeConverts.clear();
tileID = meta.getValue("id");
tileCategory = TerrainType.Category.valueOf(meta.getValue("Category"));
String rgbString = meta.getValue("rgb");
tileRGB = string2RGBValue(rgbString);
String buildCostString = meta.getValue("build_cost");
if (null != buildCostString) {
tileBuildCost = Integer.parseInt(buildCostString);
} else {
tileBuildCost = -1;
}
// Check if another type is already using this rgb value..
Integer rgbInteger = new Integer(tileRGB);
if (rgbValuesAlreadyUsed.contains(rgbInteger)) {
throw new SAXException(tileID + " can't using rgb value "
+ rgbString
+ " because it is being used by another tile type!");
}
rgbValuesAlreadyUsed.add(rgbInteger);
tileROW = Integer.parseInt(meta.getValue("right-of-way"));
}

Called Methods

SelectEngineJPanel

Class: jfreerails.client.view.SelectEngineJPanel

Documentation

No documentation available

Source Code

public SelectEngineJPanel() {
initComponents();
jList1ValueChanged(null); // Disable the ok button if no engine type
// is selected.
}

testGetNumberOfKeys

Class: jfreerails.world.top.SKEYTest

Documentation

No documentation available

Source Code

public void testGetNumberOfKeys() {
assertTrue(SKEY.getNumberOfKeys() > 5);
}

initComponents

Class: jfreerails.client.view.TrainListJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
trainSummaryJPanel1 = new jfreerails.client.view.TrainSummaryJPanel();
closeJButton = new javax.swing.JButton();
showDetails = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
trainNumLabel = new javax.swing.JLabel();
trainHeadingLabel = new javax.swing.JLabel();
maintenanceLabel = new javax.swing.JLabel();
incomeLabel = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(510, 300));
closeJButton.setText("Close");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(closeJButton, gridBagConstraints);
showDetails.setText("Show details");
showDetails.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showDetailsActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(showDetails, gridBagConstraints);
jList1
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.setCellRenderer(trainSummaryJPanel1);
jList1.setDoubleBuffered(true);
jList1.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
jList1KeyPressed(evt);
}
});
jList1
.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(
javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jList1.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
jList1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jList1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
trainNumLabel.setText("Train Number");
trainNumLabel.setMaximumSize(new java.awt.Dimension(500, 500));
trainNumLabel.setPreferredSize(new java.awt.Dimension(100, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5);
add(trainNumLabel, gridBagConstraints);
trainHeadingLabel.setText("Headed For");
trainHeadingLabel.setPreferredSize(new java.awt.Dimension(100, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
add(trainHeadingLabel, gridBagConstraints);
maintenanceLabel.setText("Maintenance YTD");
maintenanceLabel.setPreferredSize(new java.awt.Dimension(100, 14));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(0, 5, 0, 5);
add(maintenanceLabel, gridBagConstraints);
incomeLabel.setText("Income YTD");
incomeLabel.setPreferredSize(new java.awt.Dimension(100, 14));
add(incomeLabel, new java.awt.GridBagConstraints());
}// GEN-END:initComponents

paintComponent

Class: jfreerails.client.view.CashJLabel

Documentation

No documentation available

Source Code

@Override
protected void paintComponent(Graphics g) {
if (null != w) {
Money m = w.getCurrentBalance(principal);
String s = m.toString();
this.setText("$" + s);
}
super.paintComponent(g);
}

equals

Class: jfreerails.world.common.GameCalendar

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof GameCalendar) {
GameCalendar test = (GameCalendar) o;
if (this.startYear != test.startYear
|| this.ticksPerYear != test.ticksPerYear) {
return false;
}
return true;
}
return false;
}

Called Methods

No outgoing method calls

createDateJLabel

Class: experimental.SimpleComponentFactoryImpl2

Documentation

No documentation available

Source Code

public JLabel createDateJLabel() {
return null;
}

Called Methods

No outgoing method calls

sizeD1

Class: jfreerails.util.List3DImpl

Documentation

No documentation available

Source Code

public int sizeD1() {
return elementData.size();
}

Called Methods

No outgoing method calls

assertHasNextEqualsFalse

Class: jfreerails.world.train.PathWalkerImplTest

Documentation

No documentation available

Source Code

void assertHasNextEqualsFalse(ArrayList<Point> points) {
FreerailsPathIterator it2 = FreerailsPathIteratorImpl
.forwardsIterator(points);
assertTrue(!it2.hasNext());
pw = new PathWalkerImpl(it2);
pw.stepForward(100);
assertTrue(!pw.hasNext());
}

testIsPackageNameOk

Class: experimental.GenerateDependenciesXmlAndHtmlTest

Documentation

No documentation available

Source Code

public void testIsPackageNameOk() {
assertTrue(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/*"));
assertFalse(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails.*"));
assertTrue(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/trees/*"));
assertFalse(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/trees/branches*"));
assertTrue(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/trees/branches/*"));
assertFalse(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/trees/branches/**/"));
assertTrue(GenerateDependenciesXmlAndHtml
.isPackageNameOk("jfreerails/trees/branches/**/*"));
assertTrue(GenerateDependenciesXmlAndHtml
.isPackageNameOk("it/unimi/dsi/fastUtil/*")); // note upper
// case in
// package name.
}

GrowableBase

Class: jfreerails.util.GrowableBase

Documentation

/**
* Copy (clone) constructor.
*
* @param base
* instance being copied
*/

Source Code

/**
* Copy (clone) constructor.
*
* @param base
* instance being copied
*/
public GrowableBase(GrowableBase base) {
this(base.countLimit, base.maximumGrowth, base.getArray().getClass()
.getComponentType());
}

getRightOfWay

Class: jfreerails.world.terrain.NullTerrainType

Documentation

No documentation available

Source Code

public int getRightOfWay() {
return 0;
}

Called Methods

No outgoing method calls

uGet

Class: jfreerails.util.List2DDiff

Documentation

No documentation available

Source Code

@Override
T uGet(int... i) {
if (i.length != 2)
throw new IllegalArgumentException(String.valueOf(i.length));
return underlyingList.get(i[0], i[1]);
}

run

Class: jfreerails.network.InetConnectionAccepter

Documentation

No documentation available

Source Code

public void run() {
Thread.currentThread().setName(
"InetConnectionAccepter, port " + serverSocket.getLocalPort());
try {
logger.fine("Accepting connections on port "
+ serverSocket.getLocalPort());
while (isKeepRunning()) {
Socket socket = serverSocket.accept();
logger.fine("Incoming connection from "
+ socket.getRemoteSocketAddress());
synchronized (this) {
synchronized (gameServer) {
InetConnection2Client connection = new InetConnection2Client(
socket);
gameServer.addConnection(connection);
}
}
}
} catch (IOException e) {
try {
stop();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}

closeContent

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void closeContent() {
if (null != dialogueJInternalFrame) {
dialogueJInternalFrame.setVisible(false);
frame.getLayeredPane().remove(dialogueJInternalFrame);
dialogueJInternalFrame.dispose();
}
if (null != defaultFocusOwner) {
defaultFocusOwner.requestFocus();
}
}

Called Methods

No outgoing method calls

getScaledImage

Class: jfreerails.client.common.ImageManager

Documentation

No documentation available

Source Code

Image getScaledImage(String relativeFilename, int height)
throws IOException;

Called Methods

No outgoing method calls

start_TrackSet

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* A container element start event handling method.
*
* @param meta
* attributes
*/

Source Code

/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_TrackSet(final Attributes meta) throws SAXException;

Called Methods

No outgoing method calls

testSendingMoves

Class: jfreerails.network.specifics.FreerailsClientWithLocalServerTest

Documentation

/** Tests sending moves between client and server. */

Source Code

/** Tests sending moves between client and server. */
public void testSendingMoves() {
try {
/* Set up and start a game with 2 clients. */
FreerailsClient client0 = new FreerailsClient();
LogOnResponse response0 = client0.connect(server, "client0",
"password");
assertTrue(response0.isSuccessful());
FreerailsClient client1 = new FreerailsClient();
LogOnResponse response1 = client1.connect(server, "client1",
"password");
assertTrue(response1.isSuccessful());
client0.update();
client1.update();
ImStringList mapNames = (ImStringList) client0
.getProperty(ClientProperty.MAPS_AVAILABLE);
Message2Server message2 = new NewGameMessage2Server(99, mapNames
.get(0));
client0.write(message2);
server.update();
client0.update();
client1.update();
/* Now try sending some moves. */
World world = client0.getWorld();
Player player0 = world.getPlayer(0);
FreerailsPrincipal principal0 = player0.getPrincipal();
Transaction t = new Receipt(new Money(100),
Transaction.Category.MISC_INCOME);
Move move = new AddTransactionMove(principal0, t);
World copyOfWorld = world.defensiveCopy();
assertEquals(copyOfWorld, world);
MoveStatus status = move.doMove(copyOfWorld, principal0);
assertTrue(status.isOk());
// client0.write(move);
client0.processMove(move);
server.update();
MoveStatus reply = (MoveStatus) client0.read();
assertEquals(MoveStatus.MOVE_OK, reply);
client0.processMessage(reply);
/*
* After performing an update, the server and 2 clients' copies of
* the world object should be in the same state.
*/
server.update();
client0.update();
client1.update();
assertEquals(copyOfWorld, world);
assertEquals(copyOfWorld, client1.getWorld());
assertEquals(copyOfWorld, server.getCopyOfWorld());
/* Test disconnecting and reconnecting during play. */
client0.disconnect();
client1.processMove(move);
// client1.write(move);
move.doMove(client1.getWorld(), principal0);
client1.update();
server.update();
client1.update();
assertFalse(world.equals(client1.getWorld()));
response0 = client0.connect(server, "client0", "password");
assertTrue(response0.isSuccessful());
assertEquals(0, response0.getPlayerID());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}

getIndex

Class: jfreerails.world.top.NonNullElements

Documentation

No documentation available

Source Code

public int getIndex() {
return index;
}

Called Methods

No outgoing method calls

exitForm

Class: jfreerails.client.top.ClientJFrame

Documentation

/** Exit the Application. */

Source Code

/** Exit the Application. */
private void exitForm(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_exitForm
System.exit(0);
}// GEN-LAST:event_exitForm

Called Methods

No outgoing method calls

StationBuildAction

Class: jfreerails.client.view.StationBuildAction

Documentation

No documentation available

Source Code

StationBuildAction() {
setEnabled(false);
}

Called Methods

No outgoing method calls

savedmapsJListValueChanged

Class: jfreerails.launcher.SelectMapJPanel

Documentation

No documentation available

Source Code

private void savedmapsJListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_savedmapsJListValueChanged
if(savedmapsJList.getSelectedIndex() != -1)
newmapsJList.clearSelection();
validateInput();
}//GEN-LAST:event_savedmapsJListValueChanged

getRate

Class: jfreerails.controller.CargoElementObject

Documentation

No documentation available

Source Code

public int getRate() {
return rate;
}

Called Methods

No outgoing method calls

getTrackTypeName

Class: jfreerails.client.renderer.TrackPieceRendererImpl

Documentation

No documentation available

Source Code

private String getTrackTypeName() {
return typeName;
}

Called Methods

No outgoing method calls

StationModel

Class: jfreerails.world.station.StationModel

Documentation

No documentation available

Source Code

public StationModel(StationModel s, SupplyAtStation supply) {
this.supply = supply;
this.demand = s.demand;
this.cargoBundleNumber = s.cargoBundleNumber;
this.converted = s.converted;
this.name = s.name;
this.production = s.production;
this.x = s.x;
this.y = s.y;
}

Called Methods

No outgoing method calls

createBuildMenu

Class: jfreerails.client.top.GUIComponentFactory

Documentation

No documentation available

Source Code

JMenu createBuildMenu();

Called Methods

No outgoing method calls

write2ByteArray

Class: jfreerails.util.Utils

Documentation

No documentation available

Source Code

private static byte[] write2ByteArray(Serializable m) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ObjectOutputStream objectOut = new ObjectOutputStream(out);
objectOut.writeObject(m);
objectOut.flush();
} catch (IOException e) {
// Should never happen.
e.printStackTrace();
throw new IllegalStateException();
}
byte[] bytes = out.toByteArray();
return bytes;
}

Called Methods

No outgoing method calls

BuildMenu

Class: jfreerails.client.top.BuildMenu

Documentation

No documentation available

Source Code

public BuildMenu() {
super();
}

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.top.StationTypesPopup

Documentation

No documentation available

Source Code

public void setup(ModelRoot mr, ActionRoot actionRoot,
StationRadiusRenderer srr) {
modelRoot = mr;
stationBuildModel = actionRoot.getStationBuildModel();
stationRadiusRenderer = srr;
this.removeAll();
this.removePopupMenuListener(popupMenuListener);
popupMenuListener = new PopupMenuListener() {
public void popupMenuCanceled(PopupMenuEvent e) {
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
stationRadiusRenderer.hide();
stationBuildModel.getStationCancelAction().actionPerformed(
new ActionEvent(StationTypesPopup.this,
ActionEvent.ACTION_PERFORMED, ""));
}
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
stationRadiusRenderer.setPosition(tileToBuildStationOn.x,
tileToBuildStationOn.y);
stationBuildModel
.getStationBuildAction()
.putValue(
StationBuildModel.StationBuildAction.STATION_POSITION_KEY,
tileToBuildStationOn);
}
};
this.addPopupMenuListener(popupMenuListener);
final Action[] stationChooseActions = stationBuildModel
.getStationChooseActions();
for (int i = 0; i < stationChooseActions.length; i++) {
final StationBuildMenuItem rbMenuItem = new StationBuildMenuItem();
final int index = i;
rbMenuItem.configurePropertiesFromAction(stationChooseActions[i]);
rbMenuItem.setIcon(null);
// Show the relevant station radius when the station type's
// menu item gets focus.
rbMenuItem.addChangeListener(new ChangeListener() {
private boolean armed = false;
public void stateChanged(ChangeEvent e) {
if (rbMenuItem.isArmed() && (rbMenuItem.isArmed() != armed)) {
stationChooseActions[index]
.actionPerformed(new ActionEvent(rbMenuItem,
ActionEvent.ACTION_PERFORMED, ""));
}
armed = rbMenuItem.isArmed();
}
});
rbMenuItem.addActionListener(stationBuildModel
.getStationBuildAction());
add(rbMenuItem);
}
stationBuildModel.getStationBuildAction().addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if (e
.getPropertyName()
.equals(
StationBuildModel.StationBuildAction.STATION_RADIUS_KEY)) {
int newRadius = ((Integer) e.getNewValue())
.intValue();
stationRadiusRenderer.setRadius(newRadius);
}
if (stationBuildModel.getStationBuildAction()
.isEnabled()) {
stationRadiusRenderer.show();
} else {
stationRadiusRenderer.hide();
}
}
});
}

setTotalsArrayLength

Class: jfreerails.world.top.TransactionAggregator

Documentation

/**
* Creates a new array with the specified length to store monetary totals
* and sets the running total to zero. Subclasses that aggregate other
* quantities should override this method and create the appropriate arrays.
*/

Source Code

/**
* Creates a new array with the specified length to store monetary totals
* and sets the running total to zero. Subclasses that aggregate other
* quantities should override this method and create the appropriate arrays.
*/
protected void setTotalsArrayLength(int length) {
monetaryTotals = new Money[length];
runningTotal = 0;
}

Called Methods

No outgoing method calls

checkCalcSCalcVandCalcA

Class: jfreerails.world.train.ConstAccTest

Documentation

No documentation available

Source Code

private static void checkCalcSCalcVandCalcA(SpeedAgainstTime sat, double t){
boolean exceptionExpected = (t < 0) || ( t > sat.getT());
try{
double actualS = sat.calcS(t);
assertTrue(actualS >= 0);
assertTrue(actualS <= sat.getS());
assertFalse(exceptionExpected);
}catch (IllegalArgumentException e) {
assertTrue(exceptionExpected);
}
//Also check getV and getA
try{
double v = sat.calcV(t);
assertTrue(v >= 0);
assertFalse(exceptionExpected);
}catch (IllegalArgumentException e) {
assertTrue(exceptionExpected);
}
try{
sat.calcA(t);
assertFalse(exceptionExpected);
}catch (IllegalArgumentException e) {
assertTrue(exceptionExpected);
}
}

getOwnerID

Class: jfreerails.world.track.NullTrackPiece

Documentation

No documentation available

Source Code

public int getOwnerID() {
return NO_OWNER;
}

Called Methods

No outgoing method calls

renderTile

Class: jfreerails.client.renderer.AbstractTileRenderer

Documentation

No documentation available

Source Code

public void renderTile(java.awt.Graphics g, int screenX, int screenY,
int mapX, int mapY, ReadOnlyWorld w) {
Image icon = this.getIcon(mapX, mapY, w);
if (null != icon) {
g.drawImage(icon, screenX, screenY, null);
}
}

getState

Class: jfreerails.world.top.ActivityIteratorImpl

Documentation

No documentation available

Source Code

public FreerailsSerializable getState(double t) {
double dt = absolute2relativeTime(t);
return ant.act.getState(dt);
}

Called Methods

isBuilding

Class: jfreerails.client.renderer.BuildTrackController

Documentation

/**
* returns <code>true</code> if the track is being build - it is iff the
* build track is shown
*
* @return boolean
*/

Source Code

/**
* returns <code>true</code> if the track is being build - it is iff the
* build track is shown
*
* @return boolean
*/
public boolean isBuilding() {
return visible;
}

Called Methods

No outgoing method calls

testReadFromClient

Class: jfreerails.network.LocalConnectionTest

Documentation

No documentation available

Source Code

public void testReadFromClient() {
FreerailsSerializable[] objectsRead;
try {
objectsRead = localConnection.readFromClient();
assertNotNull(objectsRead);
assertTrue(Arrays.equals(EmptyArray, objectsRead));
Money m = new Money(100);
localConnection.writeToServer(m); // From the client.
objectsRead = localConnection.readFromClient();
FreerailsSerializable[] expectedArray = {m};
assertEquals(expectedArray.length, objectsRead.length);
assertTrue(Arrays.equals(expectedArray, objectsRead));
objectsRead = localConnection.readFromClient();
assertTrue(Arrays.equals(EmptyArray, objectsRead));
} catch (Exception e) {
e.printStackTrace();
fail();
}
}

addJFrame

Class: jfreerails.client.common.RepaintManagerForActiveRendering

Documentation

No documentation available

Source Code

public static synchronized void addJFrame(JFrame f) {
activelyRenderedComponents.add(f);
}

Called Methods

No outgoing method calls

CargoWaitingAndDemandedJPanel

Class: jfreerails.client.view.CargoWaitingAndDemandedJPanel

Documentation

No documentation available

Source Code

public CargoWaitingAndDemandedJPanel() {
initComponents();
}

testEquals

Class: jfreerails.world.train.TrainPositionOnMapTest

Documentation

No documentation available

Source Code

public void testEquals() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
b = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
c = TrainPositionOnMap.createInstance(new int[] { 30, 40 }, new int[] {
33, 44 });
assertTrue(!a.equals(null));
assertTrue(!a.equals(new Object()));
assertTrue(a.equals(a));
assertTrue(a.equals(b));
assertTrue(!a.equals(c));
}

getScheduleID

Class: jfreerails.world.train.TrainModel

Documentation

No documentation available

Source Code

public int getScheduleID() {
return scheduleId;
}

Called Methods

No outgoing method calls

setServerGameModel

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public void setServerGameModel(ServerGameModel serverGameModel) {
this.serverGameModel = serverGameModel;
MoveReceiver moveExecutor = new MoveReceiver() {
public void processMove(Move move) {
MoveStatus ms = move.doMove(getWorld(), Player.AUTHORITATIVE);
if (ms.ok) {
send2All(move);
} else {
logger.warning(ms.message);
}
}
};
serverGameModel.init(moveExecutor);
}

GenerateDependenciesXmlAndHtml

Class: experimental.GenerateDependenciesXmlAndHtml

Documentation

No documentation available

Source Code

private GenerateDependenciesXmlAndHtml(String xmlFilename,
String htmlFilename) throws FileNotFoundException {
Date d = new Date();
sig = this.getClass().getName() + " on " + d;
// Setup writers
File xmlFile = new File(xmlFilename);
xmlWriter = new PrintWriter(new FileOutputStream(xmlFile));
File htmlFile = new File(htmlFilename);
htmlWriter = new PrintWriter(new FileOutputStream(htmlFilename));
String[] basePackages = { "jfreerails/util/*" };
start();
startBlock("All");
add(basePackages);
add("jfreerails/world/**/*");
add("jfreerails/move/**/*");
add("jfreerails/controller/*");
add("jfreerails/network/*");
add(new String[] { "jfreerails/server/**/*", "jfreerails/client/**/*" });
add("jfreerails/launcher/**/*");
add("jfreerails/experimental/**/*");
endBlock();
startBlock("World");
add(basePackages);
add("jfreerails/world/common/*");
add(new String[] { "jfreerails/world/terrain/*",
"jfreerails/world/cargo/*", "jfreerails/world/train/*",
"jfreerails/world/station/*" });
add("jfreerails/world/track/*");
add("jfreerails/world/accounts/*");
add("jfreerails/world/player/*");
add("jfreerails/world/top/*");
endBlock();
startBlock("Server");
add(basePackages);
add("jfreerails/world/**/*");
add("jfreerails/move/**/*");
add("jfreerails/controller/*");
add("jfreerails/network/*");
add("jfreerails/server/common/*");
add("jfreerails/server/parser/*");
add("jfreerails/server/*");
endBlock();
startBlock("Client");
add(basePackages);
add("jfreerails/world/**/*");
add("jfreerails/move/**/*");
add("jfreerails/controller/*");
add("jfreerails/network/*");
add("jfreerails/client/common/*");
add("jfreerails/client/renderer/*");
add("jfreerails/client/view/*");
add("jfreerails/client/top/*");
endBlock();
finish();
xmlWriter.flush();
htmlWriter.flush();
logger.info(sig);
logger.info("Wrote " + xmlFile);
logger.info("Wrote " + htmlFile);
}

okButtonAction

Class: jfreerails.client.view.SelectWagonsJPanel

Documentation

No documentation available

Source Code

private void okButtonAction(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_okButtonAction
// Add your handling code here:
} // GEN-LAST:event_okButtonAction

Called Methods

No outgoing method calls

run

Class: jfreerails.client.top.GameLoop

Documentation

No documentation available

Source Code

public void run() {
try {
SynchronizedEventQueue.use();
RepaintManagerForActiveRendering.addJFrame(screenHandler.frame);
RepaintManagerForActiveRendering.setAsCurrentManager();
if (!screenHandler.isInUse()) {
screenHandler.apply();
}
gameNotDone = true;
fPScounter = new FPScounter();
/*
* Reduce this threads priority to avoid starvation of the input
* thread on Windows.
*/
try {
Thread.currentThread().setPriority(Thread.NORM_PRIORITY - 1);
} catch (SecurityException e) {
logger.warning("Couldn't lower priority of redraw thread");
}
while (true) {
// stats.record();
frameStartTime = System.currentTimeMillis();
/*
* Flush all redraws in the underlying toolkit. This reduces X11
* lag when there isn't much happening, but is expensive under
* Windows
*/
Toolkit.getDefaultToolkit().sync();
synchronized (SynchronizedEventQueue.MUTEX) {
if (!gameNotDone) {
SynchronizedEventQueue.MUTEX.notify();
break;
}
for (int i = 0; i < model.length; i++) {
model[i].update();
}
if (!screenHandler.isMinimised()) {
if (screenHandler.isInUse()) {
boolean contentsRestored = false;
do {
Graphics g = screenHandler.getDrawGraphics();
try {
screenHandler.frame.paintComponents(g);
boolean showFps = Boolean
.parseBoolean(System
.getProperty("SHOWFPS"));
if (showFps) {
fPScounter.drawFPS((Graphics2D) g);
}
} catch (RuntimeException re) {
/*
* We are not expecting a RuntimeException
* here. If something goes wrong, lets kill
* the game straight away to avoid
* hard-to-track-down bugs.
*/
ReportBugTextGenerator
.unexpectedException(re);
} finally {
g.dispose();
}
contentsRestored = screenHandler
.contentsRestored();
} while (contentsRestored);
screenHandler.swapScreens();
fPScounter.updateFPSCounter();
}
}
}
if (screenHandler.isMinimised()) {
try {
// The window is minimised so we don't need to keep
// updating.
Thread.sleep(200);
} catch (Exception e) {
// do nothing.
}
} else if (LIMIT_FRAME_RATE) {
long deltatime = System.currentTimeMillis()
- frameStartTime;
while (deltatime < (1000 / TARGET_FPS)) {
try {
long sleeptime = (1000 / TARGET_FPS) - deltatime;
Thread.sleep(sleeptime);
} catch (Exception e) {
e.printStackTrace();
}
deltatime = System.currentTimeMillis() - frameStartTime;
}
}
// remove all events from a event queue (max 5ms)
long startEventWaitTime = System.currentTimeMillis() + 4;
while (SynchronizedEventQueue.getInstance().peekEvent() != null) {
// we have events
Thread.yield();
if (startEventWaitTime < System.currentTimeMillis()) {
break;
}
}
}
/* signal that we are done */
synchronized (loopMonitor) {
loopMonitor.notify();
}
} catch (Exception e) {
ReportBugTextGenerator.unexpectedException(e);
}
}

dispatch

Class: jfreerails.server.parser.Track_TilesParser

Documentation

No documentation available

Source Code

private void dispatch(final boolean fireOnlyIfMixed) throws SAXException {
if (fireOnlyIfMixed && buffer.length() == 0) {
return; // skip it
}
buffer.delete(0, buffer.length());
}

Called Methods

No outgoing method calls

actionPerformed

Class: jfreerails.client.view.StationChooseAction

Documentation

No documentation available

Source Code

public void actionPerformed(ActionEvent e) {
stationBuilder.setStationType(actionId);
TrackRule trackRule = (TrackRule) modelRoot.getWorld().get(
SKEY.TRACK_RULES, actionId);
// Show the relevant station radius when the station type's menu
// item
// gets focus.
stationBuildAction.putValue(StationBuildAction.STATION_RADIUS_KEY,
new Integer(trackRule.getStationRadius()));
stationBuildAction.setEnabled(true);
}

getLegalConfigurations

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

public LegalTrackConfigurations getLegalConfigurations() {
return legalConfigurations;
}

Called Methods

No outgoing method calls

createTrainsJTabPane

Class: experimental.SimpleComponentFactoryImpl2

Documentation

No documentation available

Source Code

public JTabbedPane createTrainsJTabPane() {
return null;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.train.PathOnTiles

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return start.hashCode();
}

mousePressed

Class: jfreerails.client.top.CursorMouseAdapter

Documentation

No documentation available

Source Code

@Override
public void mousePressed(MouseEvent evt
) {
if (SwingUtilities.isLeftMouseButton(evt)) {
ignoreDragging = false;
int x = evt.getX();
int y = evt.getY();
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
// only jump - no track building
moveCursorJump(new ImPoint(x / tileSize.width, y
/ tileSize.height));
mapView.requestFocus();
pressedInside = true;
/*
* Fix for bug [ 972866 ] Build track by dragging - only when
* build track selected
*/
boolean isBuildTrackModeSet = trackBuilder
.getTrackBuilderMode() == BUILD_TRACK;
if (isBuildTrackModeSet) {
buildTrack.show();
}
} else if (SwingUtilities.isRightMouseButton(evt)) {
// Cancel building track.
buildTrack.hide();
ignoreDragging = true;
setIgnoreKeyEvents(false);
}
}

testMove

Class: jfreerails.controller.AddTrainPreMoveTest

Documentation

No documentation available

Source Code

@Override
public void testMove() {
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0),
stationA, principal, defaultSchedule);
Move m = preMove.generateMove(world);
assertDoMoveIsOk(m);
assertUndoMoveIsOk(m);
assertSurvivesSerialisation(m);
}

getTrackPieceView

Class: jfreerails.client.top.RenderersRootImpl

Documentation

No documentation available

Source Code

public TrackPieceRenderer getTrackPieceView(int i) {
return trackPieceViewList.getTrackPieceView(i);
}

doMove

Class: jfreerails.move.ChangeItemInListMove

Documentation

No documentation available

Source Code

public MoveStatus doMove(World w, FreerailsPrincipal p) {
return move(after, before, w);
}

NonNullElements

Class: jfreerails.world.top.NonNullElements

Documentation

No documentation available

Source Code

public NonNullElements(SKEY k, ReadOnlyWorld world) {
if (null == k) {
throw new NullPointerException();
}
if (null == world) {
throw new NullPointerException();
}
key = null;
principal = null;
skey = k;
w = world;
}

Called Methods

No outgoing method calls

calcA

Class: jfreerails.world.train.CompositeSpeedAgainstTime

Documentation

No documentation available

Source Code

public double calcA(double t) {
checkT(t);
TandI tai = getIndex(t);
SpeedAgainstTime acc = values.get(tai.i);
return acc.calcA(tai.offset);
}

getSaveGameNames

Class: jfreerails.network.specifics.SavedGamesManager4UnitTests

Documentation

No documentation available

Source Code

public String[] getSaveGameNames() {
Object[] keys = savedGames.keySet().toArray();
String[] names = new String[keys.length];
for (int i = 0; i < names.length; i++) {
names[i] = (String) keys[i];
}
return names;
}

Called Methods

No outgoing method calls

startThread

Class: jfreerails.launcher.Launcher

Documentation

/** Starts the client in a new thread. */

Source Code

/** Starts the client in a new thread. */
private void startThread(final GUIClient guiClient) {
try {
Runnable run = new Runnable() {
public void run() {
while (null == guiClient.getWorld()) {
guiClient.update();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// do nothing
}
}
GameModel[] models = new GameModel[] { guiClient };
ScreenHandler screenHandler = guiClient.getScreenHandler();
GameLoop gameLoop = new GameLoop(screenHandler, models);
gameLoop.run();
}
};
Thread t = new Thread(run, "Client main loop");
t.start();
} catch (Exception e) {
exit(e);
}
}

hashCode

Class: jfreerails.network.specifics.NewGameMessage2Server

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + mapName.hashCode();
return result;
}

Called Methods

No outgoing method calls

undoMove

Class: jfreerails.move.UndoMove

Documentation

No documentation available

Source Code

public MoveStatus undoMove(World w, FreerailsPrincipal p) {
return move2undo.undoMove(w, p);
}

size

Class: jfreerails.world.common.ImInts

Documentation

No documentation available

Source Code

public int size() {
return ints.length;
}

Called Methods

No outgoing method calls

scheduledStop

Class: jfreerails.controller.TrainStopsHandler

Documentation

No documentation available

Source Code

private void scheduledStop() {
TrainModel train = (TrainModel) worldDiffs.get(principal, KEY.TRAINS, this.trainId);
Schedule schedule = (ImmutableSchedule) worldDiffs.get(principal, KEY.TRAIN_SCHEDULES,
train.getScheduleID());
ImInts wagonsToAdd = schedule.getWagonsToAdd();
// Loading and unloading cargo takes time, so we make the train wait for
// a few ticks.
makeTrainWait(50);
boolean autoConsist = schedule.autoConsist();
if (null != wagonsToAdd) {
int engine = train.getEngineType();
Move m = ChangeTrainMove.generateMove(this.trainId, train, engine, wagonsToAdd,
principal);
m.doMove(worldDiffs, principal);
}
updateSchedule();
int stationToGoto = schedule.getStationToGoto();
loadAndUnloadCargo(stationToGoto, true, autoConsist);
}

moveForward

Class: jfreerails.controller.BuildTrackExplorer

Documentation

No documentation available

Source Code

public void moveForward() {
if (beforeFirst) {
throw new IllegalStateException();
}
setPosition(this.getVertexConnectedByEdge());
}

showTerrainInfo

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showTerrainInfo(int x, int y) {
FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
int terrainType = tile.getTerrainTypeID();
showTerrainInfo(terrainType);
}

getFirst

Class: jfreerails.network.SynchronizedQueue

Documentation

No documentation available

Source Code

public synchronized FreerailsSerializable getFirst() {
return queue.removeFirst();
}

Called Methods

No outgoing method calls

getTrainA

Class: jfreerails.move.TrainCrashException

Documentation

No documentation available

Source Code

public int getTrainA() {
return trainA;
}

Called Methods

No outgoing method calls

finish

Class: experimental.GenerateDependenciesXmlAndHtml

Documentation

No documentation available

Source Code

private void finish() {
assert started;
assert !startedBlock;
// finish the file.
xmlWriter.write("\t\t<delete dir=\"temp\" />\n");
xmlWriter.write("\t\t<delete dir=\"dependencies\" />\n");
xmlWriter.write("\t</target>\n");
xmlWriter.write("</project>\n");
htmlWriter.write("</html>\n");
started = false;
}

Called Methods

No outgoing method calls

transferCargo

Class: jfreerails.controller.DropOffAndPickupCargoMoveGenerator

Documentation

/**
* Move the specified quantity of the specified cargotype from one bundle to
* another.
*/

Source Code

/**
* Move the specified quantity of the specified cargotype from one bundle to
* another.
*/
private static void transferCargo(int cargoTypeToTransfer, int amountToTransfer,
MutableCargoBundle from, MutableCargoBundle to) {
if (0 == amountToTransfer) {
return;
}
Iterator<CargoBatch> batches = from.toImmutableCargoBundle().cargoBatchIterator();
int amountTransferredSoFar = 0;
while (batches.hasNext() && amountTransferredSoFar < amountToTransfer) {
CargoBatch cb = batches.next();
if (cb.getCargoType() == cargoTypeToTransfer) {
int amount = from.getAmount(cb);
int amountOfThisBatchToTransfer;
if (amount < amountToTransfer - amountTransferredSoFar) {
amountOfThisBatchToTransfer = amount;
from.setAmount(cb, 0);
} else {
amountOfThisBatchToTransfer = amountToTransfer - amountTransferredSoFar;
from.addCargo(cb, -amountOfThisBatchToTransfer);
}
to.addCargo(cb, amountOfThisBatchToTransfer);
amountTransferredSoFar += amountOfThisBatchToTransfer;
}
}
}

ConstAcc

Class: jfreerails.world.train.ConstAcc

Documentation

No documentation available

Source Code

private ConstAcc(double a, double t, double u, double s) {
this.a = a;
this.finalT = t;
this.u = u;
this.finalS = s;
}

Called Methods

No outgoing method calls

getWorld

Class: jfreerails.network.specifics.ServerGameModel

Documentation

No documentation available

Source Code

World getWorld();

Called Methods

No outgoing method calls

clear

Class: jfreerails.controller.OpenList

Documentation

No documentation available

Source Code

void clear() {
queue.clear();
map.clear();
}

Called Methods

No outgoing method calls

TrainMotion

Class: jfreerails.world.train.TrainMotion

Documentation

No documentation available

Source Code

public TrainMotion(PathOnTiles path, int trainLength, double duration, SpeedTimeAndStatus.TrainActivity act){
this.path = path;
this.trainLength = trainLength;
this.activity = act;
this.distanceEngineWillTravel = 0;
this.initialPosition = path.getTotalDistance();
this.speeds = ConstAcc.STOPPED;
this.duration = duration;
}

setHeadline

Class: jfreerails.client.view.NewsPaperJPanel

Documentation

No documentation available

Source Code

public void setHeadline(String s) {
this.headline.setText(s);
}

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.view.BalanceSheetHtmlJPanel

Documentation

No documentation available

Source Code

@Override
public void setup(ModelRoot modelRoot, RenderersRoot vl, Action closeAction) {
super.setup(modelRoot, vl, closeAction);
this.modelRoot = modelRoot;
updateHtml();
}

start_CannotBuildOnTheseTerrainTypes

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* A container element start event handling method.
*
* @param meta
* attributes
*/

Source Code

/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_CannotBuildOnTheseTerrainTypes(final Attributes meta)
throws SAXException;

Called Methods

No outgoing method calls

endDocument

Class: jfreerails.server.CitySAXParser

Documentation

No documentation available

Source Code

@Override
public void endDocument() throws SAXException {
for (int i = 0; i < cities.size(); i++) {
CityModel tempCity = cities.elementAt(i);
world.add(SKEY.CITIES, new CityModel(tempCity.getCityName(),
tempCity.getCityX(), tempCity.getCityY()));
}
}

generateMove

Class: jfreerails.controller.MoveTrainPreMove

Documentation

No documentation available

Source Code

public Move generateMove(ReadOnlyWorld w) {
// Check that we can generate a move.
if (!isUpdateDue(w))
throw new IllegalStateException();
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
TrainMotion tm = ta.findCurrentMotion(Double.MAX_VALUE);
SpeedTimeAndStatus.TrainActivity activity = tm.getActivity();
switch (activity) {
case STOPPED_AT_STATION:
return moveTrain(w);
case READY:
{
// Are we at a station?
TrainStopsHandler stopsHandler = new TrainStopsHandler(trainID,
principal, new WorldDiffs(w));
ta.getStationId(Integer.MAX_VALUE);
PositionOnTrack pot = tm.getFinalPosition();
int x = pot.getX();
int y = pot.getY();
boolean atStation = stopsHandler.getStationID(x, y) >= 0;
TrainMotion nextMotion;
if (atStation) {
// We have just arrived at a station.
double durationOfStationStop = 10;
stopsHandler.arrivesAtPoint(x, y);
SpeedTimeAndStatus.TrainActivity status = stopsHandler.isWaiting4FullLoad() ? WAITING_FOR_FULL_LOAD : STOPPED_AT_STATION;
PathOnTiles path = tm.getPath();
int lastTrainLength = tm.getTrainLength();
int currentTrainLength = stopsHandler.getTrainLength();
//If we are adding wagons we may need to lengthen the path.
if(lastTrainLength < currentTrainLength){
path = TrainStopsHandler.lengthenPath(w, path, currentTrainLength);
}
nextMotion = new TrainMotion(path, currentTrainLength,
durationOfStationStop, status);
// Create a new Move object.
Move trainMove = new NextActivityMove(nextMotion, trainID,
principal);
Move cargoMove = stopsHandler.getMoves();
return new CompositeMove(trainMove, cargoMove);
}
return moveTrain(w);
}
case WAITING_FOR_FULL_LOAD:
{
TrainStopsHandler stopsHandler = new TrainStopsHandler(trainID,
principal, new WorldDiffs(w));
boolean waiting4fullLoad = stopsHandler.refreshWaitingForFullLoad();
Move cargoMove = stopsHandler.getMoves();
if(!waiting4fullLoad){
Move trainMove = moveTrain(w);
if(null != trainMove){
return new CompositeMove(trainMove, cargoMove);
}else{
return cargoMove;
}
}
stopsHandler.makeTrainWait(30);
return cargoMove;
}
default:
throw new UnsupportedOperationException(activity.toString());
}
}

showJavaSystemPropertiesActionPerformed

Class: experimental.DialogueBoxTester

Documentation

No documentation available

Source Code

private void showJavaSystemPropertiesActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showJavaSystemPropertiesActionPerformed
// Add your handling code here:
String s = ShowJavaProperties.getPropertiesHtmlString();
HtmlJPanel htmlPanel = new HtmlJPanel(s);
htmlPanel.setup(modelRoot, vl, closeCurrentDialogue);
dialogueBoxController.showContent(htmlPanel);
}// GEN-LAST:event_showJavaSystemPropertiesActionPerformed

getTypeName

Class: jfreerails.world.track.TrackRule

Documentation

No documentation available

Source Code

String getTypeName();

Called Methods

No outgoing method calls

main

Class: jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest

Documentation

No documentation available

Source Code

public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}

getIndex

Class: jfreerails.move.ListMove

Documentation

/**
* @return the index of the item which changed.
*/

Source Code

/**
* @return the index of the item which changed.
*/
int getIndex();

Called Methods

No outgoing method calls

getSize

Class: jfreerails.client.view.World2ListModelAdapter

Documentation

No documentation available

Source Code

public int getSize() {
return elements.size();
}

addOrder

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public int addOrder(TrainOrdersModel order) {
if (!canAddOrder()) {
throw new IllegalStateException();
}
int newOrderNumber = orders.size();
addOrder(newOrderNumber, order);
return newOrderNumber;
}

getCategory

Class: jfreerails.world.terrain.TerrainType

Documentation

No documentation available

Source Code

Category getCategory();

Called Methods

No outgoing method calls

ImageManagerImpl

Class: jfreerails.client.common.ImageManagerImpl

Documentation

No documentation available

Source Code

public ImageManagerImpl(String readpath) {
this(readpath, null);
}

send

Class: jfreerails.network.AbstractInetConnection

Documentation

No documentation available

Source Code

void send(FreerailsSerializable object) throws IOException {
inetConnection.send(object);
}

initComponents

Class: jfreerails.client.view.SelectWagonsJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
wagonTypesJList = new javax.swing.JList();
okjButton = new javax.swing.JButton();
clearjButton = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
setBackground(new java.awt.Color(0, 255, 51));
setMinimumSize(new java.awt.Dimension(640, 400));
setPreferredSize(new java.awt.Dimension(620, 380));
jPanel1.setLayout(new java.awt.GridBagLayout());
jPanel1.setMinimumSize(new java.awt.Dimension(170, 300));
jPanel1.setPreferredSize(new java.awt.Dimension(170, 300));
wagonTypesJList.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyTyped(java.awt.event.KeyEvent evt) {
wagonTypesJListKeyTyped(evt);
}
});
wagonTypesJList.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
wagonTypesJListMouseClicked(evt);
}
});
jScrollPane1.setViewportView(wagonTypesJList);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
jPanel1.add(jScrollPane1, gridBagConstraints);
okjButton.setText("OK");
okjButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonAction(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
jPanel1.add(okjButton, gridBagConstraints);
clearjButton.setText("Clear");
clearjButton.setActionCommand("clear");
clearjButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
jPanel1.add(clearjButton, gridBagConstraints);
jLabel1.setFont(new java.awt.Font("Dialog", 0, 10));
jLabel1.setText("The maximum train length is 6 wagons");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.insets = new java.awt.Insets(8, 8, 8, 8);
jPanel1.add(jLabel1, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new java.awt.Insets(20, 400, 70, 10);
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
add(jPanel1, gridBagConstraints);
}// GEN-END:initComponents

toString

Class: jfreerails.world.player.WorldPrincipal

Documentation

No documentation available

Source Code

@Override
public String toString() {
return principalName;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.cargo.MutableCargoBundle

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return sortedMap.size();
}

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.view.NetWorthGraphJPanel

Documentation

No documentation available

Source Code

public void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
this.submitButtonCallBack = closeAction;
ReadOnlyWorld world = modelRoot.getWorld();
companies = new ArrayList<CompanyDetails>();
GameCalendar calender = (GameCalendar) world.get(ITEM.CALENDAR);
int startYear = calender.getYear(0);
int endYear = startYear + 100;
GameTime currentTime = world.currentTime();
int currentYear = calender.getYear(currentTime.getTicks());
xAxisLabel1.setText(String.valueOf(startYear));
xAxisLabel2.setText(String.valueOf(startYear + 50));
xAxisLabel3.setText(String.valueOf(endYear));
for (int i = 0; i < world.getNumberOfPlayers(); i++) {
Color c = PlayerColors.getColor(i);
Player player = world.getPlayer(i);
String name = player.getName();
logger.fine("Adding player " + name + " to net worth graph.");
CompanyDetails cd = new CompanyDetails(name, c);
GameTime[] times = new GameTime[101];
for (int year = 0; year < 101; year++) {
int ticks = calender.getTicks(startYear + year - 1);
times[year] = new GameTime(ticks);
}
TransactionAggregator aggregator = new NetWorthCalculator(world,
player.getPrincipal());
aggregator.setTimes(times);
Money[] values = aggregator.calculateValues();
int stopYear = currentYear - startYear + 1;
for (int year = 0; year < stopYear; year++) {
cd.value[year] = values[year].getAmount();
}
companies.add(cd);
}
setAppropriateScale();
}

nextInt

Class: jfreerails.server.TrainPathFinder

Documentation

/**
* @return a PositionOnTrack packed into an int
*/

Source Code

/**
* @return a PositionOnTrack packed into an int
*/
public int nextInt() {
PositionOnTrack tempP = new PositionOnTrack(trackExplorer.getPosition());
int x = tempP.getX();
int y = tempP.getY();
ImPoint targetPoint = stopsHandler.arrivesAtPoint(x, y);
int currentPosition = tempP.getOpposite().toInt();
ReadOnlyWorld world = trackExplorer.getWorld();
PositionOnTrack[] t = FlatTrackExplorer.getPossiblePositions(world,
targetPoint);
int[] targets = new int[t.length];
for (int i = 0; i < t.length; i++) {
int target = t[i].getOpposite().toInt();
if (target == currentPosition) {
stopsHandler.updateTarget();
}
targets[i] = target;
}
FlatTrackExplorer tempExplorer = new FlatTrackExplorer(world, tempP);
int next = pathFinder.findstep(currentPosition, targets, tempExplorer);
if (next == IncrementalPathFinder.PATH_NOT_FOUND) {
trackExplorer.nextEdge();
trackExplorer.moveForward();
return trackExplorer.getVertexConnectedByEdge();
}
tempP.setValuesFromInt(next);
tempP = tempP.getOpposite();
int nextPosition = tempP.toInt();
trackExplorer.setPosition(nextPosition);
mr.processMove(stopsHandler.getMoves());
return nextPosition;
}

main

Class: experimental.GenerateTrainHighlights

Documentation

/**
* @param args the command line arguments
*/

Source Code

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ImageManager imageManager = new ImageManagerImpl(
"/experimental/", "/experimental/");
UIDefaults lookAndFeelDefaults = UIManager.getLookAndFeelDefaults();
Color selection = (Color) lookAndFeelDefaults.get("List.selectionBackground");
selection = makeTransparent(selection, 128);
String filename = "selected_%s.png";
gen(imageManager, selection, filename);
Color focus = (Color) lookAndFeelDefaults.get("TabbedPane.focus");
focus = makeTransparent(focus, 128);
filename = "focused_%s.png";
gen(imageManager, focus, filename);
try {
imageManager.writeAllImages();
} catch (IOException e) {
e.printStackTrace();
}
}

headsAreEqual

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public static boolean headsAreEqual(TrainPositionOnMap a,
TrainPositionOnMap b) {
int aHeadX = a.getX(0);
int aHeadY = a.getY(0);
int bHeadX = b.getX(0);
int bHeadY = b.getY(0);
if (aHeadX == bHeadX && aHeadY == bHeadY) {
return true;
}
return false;
}

runTests

Class: jfreerails.move.WorldDiffsMoveTest

Documentation

No documentation available

Source Code

void runTests() {
assertFalse(diffs.equals(world));
WorldDiffMove move = WorldDiffMove.generate(diffs, WorldDiffMove.Cause.Other);
// Doing the move on the world should also succeed.
World worldCopy = (World) Utils.cloneBySerialisation(world);
assertEquals(worldCopy, world);
MoveStatus ms = move.tryDoMove(worldCopy, fp1);
if(!ms.ok)
ms.printStackTrack();
assertTrue(ms.message, ms.ok);
ms = move.doMove(worldCopy, fp1);
assertTrue(ms.ok);
assertEquals(worldCopy, diffs);
// Undoing the move on the diffs should succeed.
WorldDiffs diffsCopy = (WorldDiffs) Utils.cloneBySerialisation(diffs);
assertEquals(diffsCopy, diffs);
ms = move.tryUndoMove(diffsCopy, fp1);
assertTrue(ms.message, ms.ok);
assertFalse(diffsCopy.equals(world));
ms = move.undoMove(diffsCopy, fp1);
assertTrue(ms.ok);
assertEquals(diffsCopy, world);
// The move should survive serialisation.
Object moveCopy = Utils.cloneBySerialisation(move);
assertEquals(moveCopy, move);
assertEquals(moveCopy.hashCode(), move.hashCode());
}

popNodeWithSmallestF

Class: jfreerails.controller.OpenList

Documentation

No documentation available

Source Code

int popNodeWithSmallestF() {
OpenListEntry entry = queue.remove();
int node = entry.node;
OpenListEntry removed = map.remove(node);
if (null == removed) {
System.out.println("Shizer, size =" + queue.size());
}
return node;
}

Called Methods

No outgoing method calls

forwardsIterator

Class: jfreerails.world.common.FreerailsPathIteratorImpl

Documentation

No documentation available

Source Code

public static FreerailsPathIterator forwardsIterator(List<Point> l) {
return new FreerailsPathIteratorImpl(l, true);
}

Called Methods

No outgoing method calls

flush

Class: jfreerails.network.InetConnection

Documentation

No documentation available

Source Code

synchronized void flush() throws IOException {
objectOutputStream.flush();
// deflaterOutputStream.flush();
// deflaterOutputStream.finish();
// deflaterOutputStream.flush();
}

Called Methods

No outgoing method calls

is

Class: jfreerails.controller.ModelRoot

Documentation

/**
* Tests whether the specified property has the specified value.
*/

Source Code

/**
* Tests whether the specified property has the specified value.
*/
boolean is(Property property, Object value);

Called Methods

No outgoing method calls

testRemoveTrack

Class: jfreerails.client.renderer.BuildTrackControllerTest

Documentation

No documentation available

Source Code

public void testRemoveTrack() {
// Build the track.
testBuildTrack();
// Then remove some of it.
trackBuilder.setTrackBuilderMode(BuildMode.REMOVE_TRACK);
ImPoint from = new ImPoint(15, 10);
modelRoot.setProperty(Property.CURSOR_POSITION, from);
ImPoint to = new ImPoint(20, 10);
buildTrackController.setProposedTrack(to, trackBuilder);
buildTrackController.updateUntilComplete();
assertTrue(buildTrackController.isBuildTrackSuccessful());
buildTrackController.updateWorld(trackBuilder);
}

getCategory

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

public TrackCategories getCategory() {
return TrackCategories.non;
}

Called Methods

No outgoing method calls

configurePropertiesFromAction

Class: jfreerails.client.top.StationBuildMenuItem

Documentation

No documentation available

Source Code

@Override
public void configurePropertiesFromAction(Action a) {
super.configurePropertiesFromAction(a);
}

Called Methods

No outgoing method calls

BuildTrackJPanel

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

/** Creates new form BuildTrackJPanel */

Source Code

/** Creates new form BuildTrackJPanel */
public BuildTrackJPanel() {
initComponents();
}

FlowRateInputStream

Class: jfreerails.util.FlowRateInputStream

Documentation

No documentation available

Source Code

public FlowRateInputStream(InputStream in) {
this(in, "FlowRateInputStream", 60, 1000);
}

getPrincipal

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

FreerailsPrincipal getPrincipal() {
return world.getPlayer(0).getPrincipal();
}

isPlayer

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public boolean isPlayer(FreerailsPrincipal p) {
if (p.getWorldIndex() >= 0 && p.getWorldIndex() < players.size()) {
return true;
} else {
return false;
}
}

getPosition

Class: jfreerails.controller.GraphExplorer

Documentation

/** Return the current edge. */

Source Code

/** Return the current edge. */
int getPosition();

Called Methods

No outgoing method calls

setArray

Class: jfreerails.util.IntArray

Documentation

/**
* Set the backing array. This method is used by the type-agnostic base
* class code to set the array used for type-specific storage.
*
*/

Source Code

/**
* Set the backing array. This method is used by the type-agnostic base
* class code to set the array used for type-specific storage.
*
*/
@Override
protected final void setArray(Object array) {
baseArray = (int[]) array;
}

Called Methods

No outgoing method calls

setUp

Class: jfreerails.controller.StockPriceCalculatorTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
super.setUp();
w = MapFixtureFactory2.getCopy();
calc = new StockPriceCalculator(w);
}

assertTryMoveFails

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

protected void assertTryMoveFails(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertTrue("Move went through when it should have failed", !ms.ok);
}

start_CannotBuildOnTheseTerrainTypes

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void start_CannotBuildOnTheseTerrainTypes(final Attributes meta)
throws SAXException {
terrainTypes = new java.util.HashSet<TerrainType.Category>();
}

Called Methods

No outgoing method calls

addD2

Class: jfreerails.util.List3DImpl

Documentation

No documentation available

Source Code

public int addD2(int d1) {
ArrayList<ArrayList<T>> dim2 = elementData.get(d1);
dim2.add(new ArrayList<T>() );
return dim2.size()-1;
}

Called Methods

No outgoing method calls

testGetOpposite

Class: jfreerails.world.common.PositionOnTrackTest

Documentation

No documentation available

Source Code

public void testGetOpposite() {
PositionOnTrack p1 = PositionOnTrack.createComingFrom(10, 10,
Step.NORTH);
PositionOnTrack p2 = p1.getOpposite();
assertNotNull(p2);
PositionOnTrack p3 = PositionOnTrack.createComingFrom(10, 11,
Step.SOUTH);
assertEquals(p3, p2);
}

nextStep

Class: jfreerails.controller.MoveTrainPreMove2ndTest

Documentation

No documentation available

Source Code

private Step nextStep() {
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
Step step = preMove.nextStep(world);
return step;
}

getY

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public int getY(int position) {
return ypoints.get(position);
}

getStationBuildModel

Class: jfreerails.client.view.ActionRoot

Documentation

No documentation available

Source Code

public StationBuildModel getStationBuildModel() {
return stationBuildModel;
}

Called Methods

No outgoing method calls

wagonTypesJListKeyTyped

Class: jfreerails.client.view.SelectWagonsJPanel

Documentation

No documentation available

Source Code

private void wagonTypesJListKeyTyped(java.awt.event.KeyEvent evt) { // GEN-FIRST:event_wagonTypesJListKeyTyped
// Add your handling code here:
if (KeyEvent.VK_ENTER == evt.getKeyCode()) {
addwagon();
} else {
}
} // GEN-LAST:event_wagonTypesJListKeyTyped

hashCode

Class: jfreerails.world.accounts.Bill

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = amount.hashCode();
result = 29 * result + category.hashCode();
return result;
}

dumpImages

Class: jfreerails.client.renderer.ChequeredTileRenderer

Documentation

No documentation available

Source Code

@Override
public void dumpImages(ImageManager imageManager) {
for (int i = 0; i < this.getTileIcons().length; i++) {
String fileName = generateRelativeFileName(i);
imageManager.setImage(fileName, this.getTileIcons()[i]);
}
}

incrementFramCt

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public void incrementFramCt() {
if (frame > 0) {
incrementFrame();
frame = 0;
} else {
frame++;
}
}

EngineType

Class: jfreerails.world.train.EngineType

Documentation

No documentation available

Source Code

public EngineType(String name, int power, Money m, int speed, Money maint) {
engineTypeName = name;
powerAtDrawbar = power;
price = m;
maxSpeed = speed;
maintenance = maint;
}

Called Methods

No outgoing method calls

endBlock

Class: experimental.GenerateDependenciesXmlAndHtml

Documentation

No documentation available

Source Code

private void endBlock() {
assert started;
assert startedBlock;
htmlWriter
.write("<table width=\"100%\" border=\"1\" cellpadding=\"10\" cellspacing=\"10\" bordercolor=\"#333333\" bgcolor=\"#FFFFFF\">\n");
for (int i = packages.size() - 1; i >= 0; i--) {
String packageName = packages.get(i);
htmlWriter.write("<tr bgcolor=\"#FFCCCC\"> \n");
htmlWriter.write("<td height=\"50\" bgcolor=\"#FFCC66\">"
+ packageName + "</td>\n");
htmlWriter.write("</tr>\n");
}
htmlWriter.write("</table>\n");
packages.clear();
xmlWriter.write("\n\t\t<!-- End Block -->\n");
xmlWriter.write("\t\t<echo message=\"End Block\"/>\n");
startedBlock = false;
}

Called Methods

No outgoing method calls

CargoElementObject

Class: jfreerails.controller.CargoElementObject

Documentation

No documentation available

Source Code

public CargoElementObject(int rate, int type) {
this.rate = rate;
this.type = type;
}

Called Methods

No outgoing method calls

getTerrainTypeName

Class: jfreerails.world.terrain.TerrainType

Documentation

No documentation available

Source Code

String getTerrainTypeName();

Called Methods

No outgoing method calls

setUp

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
underlying = new List2DImpl<Object>(0);
map = new TreeMap<ListKey, Object>();
diffs = new List2DDiff<Object>(map, underlying, listid.test);
}

Called Methods

No outgoing method calls

updateIfNecessary

Class: jfreerails.client.view.TrainDescriptionJPanel

Documentation

No documentation available

Source Code

private void updateIfNecessary() {
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
trainNumber);
for (int i = 0; i < train.getNumberOfWagons(); i++) {
// this.sideOnTrainViewJPanel1.addWagon(train.getWagon(i));
}
int cargoBundleID = train.getCargoBundleID();
FreerailsSerializable cb = w.get(
principal, KEY.CARGO_BUNDLES, cargoBundleID);
if(train != lastTrain || cb != lastCargoBundle)
displayTrain(trainNumber);
}

QuickRGBTileRendererList

Class: jfreerails.client.top.QuickRGBTileRendererList

Documentation

No documentation available

Source Code

public QuickRGBTileRendererList(ReadOnlyWorld w) {
int numberOfTerrainTypes = w.size(SKEY.TERRAIN_TYPES);
rgbValues = new int[numberOfTerrainTypes];
images = new Image[numberOfTerrainTypes];
for (int i = 0; i < numberOfTerrainTypes; i++) {
TerrainType t = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
rgbValues[i] = t.getRGB();
images[i] = createImageFor(t);
rgb2index.put(new Integer(t.getRGB()), new Integer(i));
}
}

MutableCargoBundle

Class: jfreerails.world.cargo.MutableCargoBundle

Documentation

No documentation available

Source Code

public MutableCargoBundle(ImmutableCargoBundle imcb) {
this();
Iterator<CargoBatch> it = imcb.cargoBatchIterator();
while (it.hasNext()) {
CargoBatch cb = it.next();
addCargo(cb, imcb.getAmount(cb));
}
}

CityTilePositioner

Class: jfreerails.server.CityTilePositioner

Documentation

No documentation available

Source Code

public CityTilePositioner(World w) {
this.w = w;
// get the different types of Urban/Industry/Resource terrain
for (int i = 0; i < w.size(SKEY.TERRAIN_TYPES); i++) {
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
switch (type.getCategory().ordinal()) {
case 0:
urbanTerrainTypes.add(type);
break;
case 6:
industryTerrainTypes.add(type);
break;
case 7:
resourceTerrainTypes.add(type);
break;
}
}
}

get8bitTemplate

Class: jfreerails.world.common.Step

Documentation

No documentation available

Source Code

public int get8bitTemplate() {
return 1 << this.getID();
}

tryUndoMove

Class: jfreerails.move.CompositeMove

Documentation

No documentation available

Source Code

public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = undoMove(w, p);
if (ms.isOk()) {
redoMoves(w, 0, p);
}
return ms;
}

getKey

Class: jfreerails.world.top.TypeID

Documentation

No documentation available

Source Code

public SKEY getKey() {
return key;
}

Called Methods

No outgoing method calls

upgradeStation

Class: jfreerails.controller.AddStationPreMove

Documentation

No documentation available

Source Code

public static AddStationPreMove upgradeStation(ImPoint p, int trackRule,
FreerailsPrincipal principal) {
return new AddStationPreMove(p, trackRule, principal);
}

Called Methods

No outgoing method calls

isBuildTrackSuccessful

Class: jfreerails.client.renderer.BuildTrackController

Documentation

/** Returns true if all the track pieces can be successfully built. */

Source Code

/** Returns true if all the track pieces can be successfully built. */
public boolean isBuildTrackSuccessful() {
return isBuildTrackSuccessful;
}

Called Methods

No outgoing method calls

testLists

Class: jfreerails.server.MapFixtureFactory2Test

Documentation

No documentation available

Source Code

public void testLists() {
assertTrue(w1.size(SKEY.CARGO_TYPES) > 0);
assertTrue(w1.size(SKEY.TRACK_RULES) > 0);
assertTrue(w1.size(SKEY.TERRAIN_TYPES) > 0);
}

testPreMoves1

Class: jfreerails.network.specifics.MovePrecommitterTest

Documentation

No documentation available

Source Code

public void testPreMoves1() {
PreMove pm = TimeTickPreMove.INSTANCE;
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
committer.fromServer(pm);
assertEquals(newTime, getTime());
}

tryDoMove

Class: jfreerails.move.NextActivityMove

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
// Check that active entity exists.
if (w.size(principal) <= index)
return MoveStatus.moveFailed("Index out of range. "+w.size(principal)+"<= "+index);
return MoveStatus.MOVE_OK;
}

handle_Cargo

Class: jfreerails.server.parser.CargoAndTerrainHandlerImpl

Documentation

No documentation available

Source Code

public void handle_Cargo(final Attributes meta) throws SAXException {
String cargoID = meta.getValue("id");
String cargoCategory = meta.getValue("Category");
int unitWeight = Integer.parseInt(meta.getValue("unitWeight"));
CargoType cargoType = new CargoType(unitWeight, cargoID, Categories
.getCategory(cargoCategory));
int cargoNumber = world.size(SKEY.CARGO_TYPES);
cargoName2cargoTypeNumber.put(cargoID, new Integer(cargoNumber));
world.add(SKEY.CARGO_TYPES, cargoType);
}

Called Methods

paintRectangleOfTiles

Class: jfreerails.client.renderer.TrackLayer

Documentation

No documentation available

Source Code

private void paintRectangleOfTiles(Graphics g, int x, int y, int width,
int height) {
paintRectangleOfTiles(g, new Rectangle(x, y, width, height));
}

Called Methods

  • jfreerails.client.renderer.MapBackgroundRender.TrackLayer.paintRectangleOfTiles (external)

getMove

Class: jfreerails.move.ChangeGameSpeedMove

Documentation

No documentation available

Source Code

public static ChangeGameSpeedMove getMove(ReadOnlyWorld w,
GameSpeed newGameSpeed) {
return new ChangeGameSpeedMove((GameSpeed) w.get(ITEM.GAME_SPEED),
newGameSpeed);
}

size

Class: jfreerails.util.ListXDDiffs

Documentation

No documentation available

Source Code

public int size(int... i) {
ListKey sizeKey = new ListKey(ListKey.Type.EndPoint, listID, i);
if (diffs.containsKey(sizeKey)) {
Integer size = (Integer) diffs.get(sizeKey);
return size.intValue();
}
return getUnderlyingSize(i);
}

createCashJLabel

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

public JLabel createCashJLabel() {
return cashjLabel;
}

Called Methods

No outgoing method calls

propertyChange

Class: jfreerails.client.common.SoundManager

Documentation

No documentation available

Source Code

public void propertyChange(ModelRoot.Property p, Object before, Object after) {
if (p.equals(ModelRoot.Property.PLAY_SOUNDS)) {
Boolean b = (Boolean) after;
playSounds = b.booleanValue();
}
}

Called Methods

No outgoing method calls

createBuildMenu

Class: experimental.SimpleComponentFactoryImpl2

Documentation

No documentation available

Source Code

public JMenu createBuildMenu() {
return new JMenu("Build");
}

Called Methods

No outgoing method calls

keyPressed

Class: jfreerails.client.top.UserInputOnMapController

Documentation

No documentation available

Source Code

@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (isIgnoreKeyEvents()) {
if (keyCode == KeyEvent.VK_ESCAPE) {
setIgnoreKeyEvents(false);
} else {
return;
}
}
ImPoint cursorPosition = getCursorPosition();
switch (keyCode) {
case KeyEvent.VK_NUMPAD1:
moveCursorOneTile(Step.SOUTH_WEST);
break;
case KeyEvent.VK_NUMPAD2:
moveCursorOneTile(Step.SOUTH);
break;
// @SonnyZ
case KeyEvent.VK_DOWN:
if (e.getModifiers() == 2) {
moveCursorOneTile(Step.SOUTH);
}
break;
// --
case KeyEvent.VK_NUMPAD3:
moveCursorOneTile(Step.SOUTH_EAST);
break;
case KeyEvent.VK_NUMPAD4:
moveCursorOneTile(Step.WEST);
break;
// @SonnyZ
case KeyEvent.VK_LEFT:
if (e.getModifiers() == 2) {
moveCursorOneTile(Step.WEST);
}
break;
// --
case KeyEvent.VK_NUMPAD6:
moveCursorOneTile(Step.EAST);
break;
// @SonnyZ
case KeyEvent.VK_RIGHT:
if (e.getModifiers() == 2) {
moveCursorOneTile(Step.EAST);
}
break;
// --
case KeyEvent.VK_NUMPAD7:
moveCursorOneTile(Step.NORTH_WEST);
break;
case KeyEvent.VK_NUMPAD8:
moveCursorOneTile(Step.NORTH);
break;
// @SonnyZ
case KeyEvent.VK_UP:
if (e.getModifiers() == 2) {
moveCursorOneTile(Step.NORTH);
}
break;
// --
case KeyEvent.VK_NUMPAD9:
moveCursorOneTile(Step.NORTH_EAST);
break;
case KeyEvent.VK_F8: {
// Check whether we can built a station here before proceeding.
if (stationTypesPopup.canBuiltStationHere(cursorPosition.toPoint())) {
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
int x = cursorPosition.x * tileSize.width;
int y = cursorPosition.y * tileSize.height;
stationTypesPopup.showMenu(mapView, x, y, cursorPosition
.toPoint());
} else {
modelRoot.setProperty(Property.QUICK_MESSAGE, "Can't"
+ " build station here!");
}
break;
}
case KeyEvent.VK_BACK_SPACE:
logger.info("Undo building track currently not implemented.");
//
// MoveStatus ms = trackBuilder.undoLastTrackMove();
//
// if (!ms.isOk()) {
// setCursorMessage(ms.message);
// }
break;
case KeyEvent.VK_I: {
dialogueBoxController.showStationOrTerrainInfo(cursorPosition.x,
cursorPosition.y);
break;
}
case KeyEvent.VK_C: {
mapView.centerOnTile(cursorPosition.toPoint());
break;
}
case KeyEvent.VK_B: {
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
int x = cursorPosition.x * tileSize.width;
int y = cursorPosition.y * tileSize.height;
buildIndustryJPopupMenu.setCursorLocation(cursorPosition.toPoint());
buildIndustryJPopupMenu.show(mapView, x, y);
break;
}
case KeyEvent.VK_ESCAPE: {
cancelProposedBuild();
break;
}
// @author SonnyZ
case KeyEvent.VK_X: {
// modelRoot.setProperty(Property.QUICK_MESSAGE, keyCode + " was
// pressed!");
dialogueBoxController.showExitDialog();
break;
}
// @SonnyZ
case KeyEvent.VK_S: {
if (e.getModifiers() == 2) {
ServerControlModel cont = actionRoot.getServerControls();
// String name = JOptionPane.showInputDialog(null, "Saved Game
// Name:","Save
// Game",JOptionPane.QUESTION_MESSAGE,null,null,modelRoot.getPrincipal().getName()).toString();
// modelRoot.setProperty(Property.QUICK_MESSAGE, name);
cont.getSaveGameAction().actionPerformed(null);
}
break;
}
// @SonnyZ
case KeyEvent.VK_L: {
if (e.getModifiers() == 2) {
ServerControlModel cont = actionRoot.getServerControls();
cont.getLoadGameAction().actionPerformed(null);
}
break;
}
// @SonnyZ
case KeyEvent.VK_M: {
// if the screen is not clicked after the broker screen is closed
// and 'M' is pressed
// again, the broker screen will never show up again.
dialogueBoxController.showBrokerScreen();
break;
}
case KeyEvent.VK_F12: {
System.out.println("Disable keyboard input!");
setIgnoreKeyEvents(true);
break;
}
}
}

getTrackPieceView

Class: jfreerails.client.renderer.RenderersRoot

Documentation

No documentation available

Source Code

TrackPieceRenderer getTrackPieceView(int i);

Called Methods

No outgoing method calls

stopGame

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public void stopGame() {
logger.info("Stop game.");
}

Called Methods

No outgoing method calls

handle_Converts

Class: jfreerails.server.parser.CargoAndTerrainHandler

Documentation

/**
* An empty element event handling method.
*
*/

Source Code

/**
* An empty element event handling method.
*
*/
public void handle_Converts(final Attributes meta) throws SAXException;

Called Methods

No outgoing method calls

netWorth

Class: jfreerails.controller.FinancialDataGatherer

Documentation

No documentation available

Source Code

public Money netWorth() {
NetWorthCalculator nwc = new NetWorthCalculator(w, principal);
GameTime[] times = {GameTime.BIG_BANG, GameTime.END_OF_THE_WORLD};
nwc.setTimes(times);
return nwc.calculateValue();
}

UserInputOnMapController

Class: jfreerails.client.top.UserInputOnMapController

Documentation

No documentation available

Source Code

public UserInputOnMapController(ModelRoot mr, ActionRoot ar) {
modelRoot = mr;
actionRoot = ar;
}

Called Methods

No outgoing method calls

itemAdded

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void itemAdded(KEY key, int index, FreerailsPrincipal principal) {
/*
* Fix for: 910138 After building a train display train orders 910143
* After building station show supply and demand
*/
boolean rightPrincipal = principal
.equals(this.modelRoot.getPrincipal());
if (KEY.TRAINS == key && rightPrincipal) {
this.showTrainOrders(index);
} else if (KEY.STATIONS == key && rightPrincipal) {
this.showStationInfo(index);
}
}

end_ListOfTrackPieceTemplates

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void end_ListOfTrackPieceTemplates() throws SAXException {
legalTrackConfigurations = new jfreerails.world.track.LegalTrackConfigurations(
maxConsequ, legalTemplates);
legalTemplates = null;
}

Called Methods

No outgoing method calls

createReportsMenu

Class: experimental.SimpleComponentFactoryImpl2

Documentation

No documentation available

Source Code

public JMenu createReportsMenu() {
// TODO Auto-generated method stub
return null;
}

Called Methods

No outgoing method calls

getNumberOfActiveEntities

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public int getNumberOfActiveEntities(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
return activityLists.sizeD2(playerIndex);
}

loadgame

Class: jfreerails.controller.ServerControlInterface

Documentation

No documentation available

Source Code

void loadgame(String saveGameName) throws IOException;

Called Methods

No outgoing method calls

assertNearest

Class: jfreerails.world.common.StepTest

Documentation

No documentation available

Source Code

private void assertNearest(Step v, int dx, int dy) {
Step v2 = Step.getNearestVector(dx, dy);
assertEquals(v, v2);
}

start_TrackPieceTemplate

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* A container element start event handling method.
*
* @param meta
* attributes
*/

Source Code

/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_TrackPieceTemplate(final Attributes meta) throws SAXException;

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

public void setup(ModelRoot mr, RenderersRoot vl, Action al) {
trainOrderJPanel1.setup(mr, vl, null);
this.modelRoot = mr;
this.vl = vl;
// This actionListener is fired by the select station popup when a
// station is selected.
Action action = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent evt) {
sendUpdateMove(selectStationJPanel1.generateNewSchedule());
selectStationJPopupMenu.setVisible(false);
listModel.fireRefresh();
orders.requestFocus();
}
};
this.selectStationJPanel1.setup(mr, vl, action);
}

componentShown

Class: jfreerails.controller.JFrameMinimumSizeEnforcer

Documentation

No documentation available

Source Code

public void componentShown(ComponentEvent arg0) {
}

Called Methods

No outgoing method calls

tileA

Class: jfreerails.world.track.TrackSection

Documentation

No documentation available

Source Code

public ImPoint tileA(){
return tile;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.accounts.EconomicClimate

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof EconomicClimate)) {
return false;
}
final EconomicClimate economicClimate = (EconomicClimate) o;
if (baseInterestRate != economicClimate.baseInterestRate) {
return false;
}
if (name != null ? !name.equals(economicClimate.name)
: economicClimate.name != null) {
return false;
}
return true;
}

Called Methods

No outgoing method calls

setUp

Class: jfreerails.server.MapFixtureFactory2Test

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
// TODO Auto-generated method stub
super.setUp();
w1 = getCopy();
}

main

Class: experimental.RunMe

Documentation

No documentation available

Source Code

public static void main(String[] args) {
JFrame jFrame = new jfreerails.client.top.ClientJFrame(
new SimpleComponentFactoryImpl2());
// jFrame.show();
ScreenHandler screenHandler = new ScreenHandler(jFrame,
ScreenHandler.WINDOWED_MODE);
GameLoop gameLoop = new GameLoop(screenHandler);
Thread t = new Thread(gameLoop);
t.start();
}

Called Methods

No outgoing method calls

testPathOnTiles

Class: jfreerails.world.train.PathOnTilesTest

Documentation

No documentation available

Source Code

public void testPathOnTiles() {
ImPoint start = null;
Step[] vectors = null;
assertTrue(throwsException(start, vectors));
start = new ImPoint();
assertTrue(throwsException(start, vectors));
vectors = new Step[] { null, null };
assertTrue(throwsException(start, vectors));
vectors = new Step[] { NORTH, SOUTH };
assertFalse(throwsException(start, vectors));
}

hashCode

Class: jfreerails.world.station.Demand4Cargo

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result = 0;
for (int i = 0; i < demand.size(); i++) {
result = 29 * result + demand.get(i);
}
return result;
}

tryDoMove

Class: jfreerails.move.WorldDiffMove

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(World world, FreerailsPrincipal p) {
MoveStatus ms = tryMapChanges(world, false);
if (!ms.ok)
return ms;
return ms = listChanges.tryDoMove(world, p);
}

calTrainLength

Class: jfreerails.controller.AddTrainPreMove

Documentation

No documentation available

Source Code

private int calTrainLength() {
TrainModel train = new TrainModel(engineTypeId, wagons, 0);
int length = train.getLength();
return length;
}

CargoType

Class: jfreerails.world.cargo.CargoType

Documentation

No documentation available

Source Code

public CargoType(int weight, String s, Categories cat) {
unitWeight = weight;
category = cat;
name = s;
}

Called Methods

No outgoing method calls

TrainImages

Class: jfreerails.client.renderer.TrainImages

Documentation

No documentation available

Source Code

public TrainImages(ImageManager imageManager, String name) throws IOException {
sideOnFileName = TrainImages.generateSideOnFilename(name);
sideOnImage = imageManager.getImage(sideOnFileName);
for (int direction = 0; direction < 8; direction++) {
overheadImages[direction] = imageManager
.getImage(generateOverheadFilename(name, direction));
overheadSelectedImages[direction] = imageManager
.getImage(generateOverheadFilename("highlights" + File.separator + "selected", direction));
overheadFocusedImages[direction] = imageManager
.getImage(generateOverheadFilename("highlights" + File.separator + "focused", direction));
}
}

WorldImpl

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public WorldImpl() {
this(0, 0);
}

toString

Class: jfreerails.world.top.ITEM

Documentation

No documentation available

Source Code

@Override
public String toString() {
return Utils.findConstantFieldName(this);
}

getConversion

Class: jfreerails.controller.CalcCargoSupplyRateAtStation

Documentation

No documentation available

Source Code

public ConvertedAtStation getConversion() {
return new ConvertedAtStation(this.converts);
}

Called Methods

No outgoing method calls

setDocumentLocator

Class: jfreerails.server.parser.CargoAndTerrainParser

Documentation

/**
* This SAX interface method is implemented by the parser.
*
*/

Source Code

/**
* This SAX interface method is implemented by the parser.
*
*/
public final void setDocumentLocator(Locator locator) {
}

Called Methods

No outgoing method calls

MapDiff

Class: jfreerails.move.MapDiff

Documentation

No documentation available

Source Code

MapDiff(FreerailsSerializable before, FreerailsSerializable after,
ImPoint p) {
this.after = after;
this.before = before;
this.x = p.x;
this.y = p.y;
}

Called Methods

No outgoing method calls

StockPriceCalculator

Class: jfreerails.controller.StockPriceCalculator

Documentation

No documentation available

Source Code

public StockPriceCalculator(ReadOnlyWorld w){
this.w = w;
}

Called Methods

No outgoing method calls

canPullUp

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public boolean canPullUp(int orderNumber) {
boolean isAlreadyAtTop = 0 == orderNumber;
boolean isPriorityOrdersAbove = (orderNumber == 1 && this.hasPriorityOrders);
return !isAlreadyAtTop && !isPriorityOrdersAbove;
}

Called Methods

No outgoing method calls

row2index

Class: jfreerails.world.top.NonNullElements

Documentation

No documentation available

Source Code

public static int row2index(ReadOnlyWorld w, KEY key, FreerailsPrincipal p,
int row) {
int count = 0;
for (int i = 0; i < w.size(p, key); i++) {
if (w.get(p, key, i) != null) {
if (count == row) {
return i;
}
count++;
}
}
throw new NoSuchElementException(String.valueOf(row));
}

CompositeMove

Class: jfreerails.move.CompositeMove

Documentation

No documentation available

Source Code

public CompositeMove(Move... moves) {
this.moves = new ImList<Move>(moves);
}

Called Methods

No outgoing method calls

StationChooseAction

Class: jfreerails.client.view.StationChooseAction

Documentation

No documentation available

Source Code

public StationChooseAction(int actionId) {
this.actionId = actionId;
}

Called Methods

No outgoing method calls

write

Class: jfreerails.network.specifics.FreerailsClient

Documentation

No documentation available

Source Code

final void write(FreerailsSerializable fs) {
try {
connection2Server.writeToServer(fs);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException();
}
}

doPreMove

Class: jfreerails.controller.SimpleMoveExecutor

Documentation

No documentation available

Source Code

public MoveStatus doPreMove(PreMove pm) {
Move m = pm.generateMove(w);
return m.doMove(w, p);
}

testTandS

Class: jfreerails.world.train.ConstAccTest

Documentation

No documentation available

Source Code

public void testTandS() {
SpeedAgainstTime acc1 = ConstAcc.uat(0, 10, 5);
double s = acc1.getS();
SpeedAgainstTime acc2 = ConstAcc.uas(0, 10, s);
assertEquals(acc1, acc2);
acc1 = ConstAcc.uat(10, 0, 5);
assertEquals(50, acc1.getS(), 0.00001);
acc2 = ConstAcc.uas(10, 0, acc1.getS());
assertEquals(acc1, acc2);
}

display

Class: jfreerails.client.view.TrainListCellRenderer

Documentation

No documentation available

Source Code

public void display(int newTrainNumber) {
showingOrder = false;
this.trainNumber = newTrainNumber;
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS, trainNumber);
display(train.getEngineType(), train.getConsist());
resetPreferredSize();
}

isNoConsistChange

Class: jfreerails.world.train.TrainOrdersModel

Documentation

No documentation available

Source Code

public boolean isNoConsistChange() {
return null == consist;
}

Called Methods

No outgoing method calls

addBond

Class: jfreerails.controller.FinancialDataGathererTest

Documentation

/**
* Adds a bond and returns true if another bond can be added. Written to
* avoid copy & paste in testCanIssueBond().
*/

Source Code

/**
* Adds a bond and returns true if another bond can be added. Written to
* avoid copy & paste in testCanIssueBond().
*/
private boolean addBond() {
FinancialDataGatherer fdg;
w.addTransaction(player.getPrincipal(), BondTransaction.issueBond(5));
fdg = new FinancialDataGatherer(w, player.getPrincipal());
boolean canIssueBond = fdg.canIssueBond();
return canIssueBond;
}

hide

Class: jfreerails.client.renderer.StationRadiusRenderer

Documentation

No documentation available

Source Code

public void hide() {
ModelRoot.Value lastCursorMode = (ModelRoot.Value) modelRoot
.getProperty(ModelRoot.Property.PREVIOUS_CURSOR_MODE);
assert !lastCursorMode
.equals(ModelRoot.Value.PLACE_STATION_CURSOR_MODE);
modelRoot.setProperty(ModelRoot.Property.CURSOR_MODE, lastCursorMode);
modelRoot.setProperty(Property.IGNORE_KEY_EVENTS, Boolean.FALSE);
}

initComponents

Class: jfreerails.launcher.ClientOptionsJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel3 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
playerName = new javax.swing.JTextField();
playerNames = new javax.swing.JComboBox();
jPanel4 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
remoteIP = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
remotePort = new javax.swing.JTextField();
spacer = new javax.swing.JPanel();
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jPanel2 = new javax.swing.JPanel();
windowedButton = new javax.swing.JRadioButton();
fixedSizeButton = new javax.swing.JRadioButton();
fullScreenButton = new javax.swing.JRadioButton();
setLayout(new java.awt.GridBagLayout());
addComponentListener(new java.awt.event.ComponentAdapter() {
@Override
public void componentShown(java.awt.event.ComponentEvent evt) {
formComponentShown(evt);
}
});
jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));
jPanel3.setBorder(new javax.swing.border.TitledBorder(
new javax.swing.border.EtchedBorder(), "Player Details"));
jLabel1.setText("Player name:");
jPanel3.add(jLabel1);
playerName.setColumns(12);
playerName.setText(owner.getProperty("freerails.player.name"));
jPanel3.add(playerName);
playerNames.setToolTipText("Select a player from the saved game.");
jPanel3.add(playerNames);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
add(jPanel3, gridBagConstraints);
jPanel4.setLayout(new java.awt.GridBagLayout());
jPanel4
.setBorder(new javax.swing.border.TitledBorder(
new javax.swing.border.EtchedBorder(),
"Remote server address"));
jPanel4.setEnabled(false);
jLabel2.setText("IP Address:");
jPanel4.add(jLabel2, new java.awt.GridBagConstraints());
remoteIP.setColumns(15);
remoteIP.setText(owner.getProperty("freerails.server.ip.address"));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel4.add(remoteIP, gridBagConstraints);
jLabel3.setText("port");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel4.add(jLabel3, gridBagConstraints);
remotePort.setColumns(5);
remotePort.setText(owner.getProperty("freerails.server.port"));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
jPanel4.add(remotePort, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
jPanel4.add(spacer, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.weightx = 1.0;
add(jPanel4, gridBagConstraints);
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel1.setBorder(new javax.swing.border.TitledBorder(
new javax.swing.border.EtchedBorder(), "Select Display Mode"));
jScrollPane1.setBorder(new javax.swing.border.BevelBorder(
javax.swing.border.BevelBorder.LOWERED));
jList1
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.setEnabled(false);
jList1
.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(
javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jScrollPane1.setViewportView(jList1);
jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);
jPanel2.setLayout(new javax.swing.BoxLayout(jPanel2,
javax.swing.BoxLayout.Y_AXIS));
buttonGroup1.add(windowedButton);
windowedButton.setSelected(true);
windowedButton.setText("Windowed");
jPanel2.add(windowedButton);
buttonGroup1.add(fixedSizeButton);
fixedSizeButton.setText("Windowed (fixed size 640*480)");
jPanel2.add(fixedSizeButton);
buttonGroup1.add(fullScreenButton);
fullScreenButton.setText("Full screen");
fullScreenButton
.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
fullScreenButtonStateChanged(evt);
}
});
jPanel2.add(fullScreenButton);
jPanel1.add(jPanel2, java.awt.BorderLayout.NORTH);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jPanel1, gridBagConstraints);
}// GEN-END:initComponents

ArrayBase

Class: jfreerails.util.ArrayBase

Documentation

/**
* Constructor with full specification.
*
* @param size
* number of elements initially allowed in array
* @param growth
* maximum size increment for growing array
* @param type
* array element type
*/

Source Code

/**
* Constructor with full specification.
*
* @param size
* number of elements initially allowed in array
* @param growth
* maximum size increment for growing array
* @param type
* array element type
*/
public ArrayBase(int size, int growth, Class type) {
super(size, growth, type);
}

getT

Class: jfreerails.world.train.CompositeSpeedAgainstTime

Documentation

No documentation available

Source Code

public double getT() {
return finalT;
}

Called Methods

No outgoing method calls

getMapSizeInPixels

Class: jfreerails.client.renderer.BlankMapRenderer

Documentation

No documentation available

Source Code

public Dimension getMapSizeInPixels() {
int height = (int) (400 * scale);
int width = (int) (400 * scale);
return new Dimension(height, width);
}

Called Methods

No outgoing method calls

LegalTrackConfigurations

Class: jfreerails.world.track.LegalTrackConfigurations

Documentation

No documentation available

Source Code

public LegalTrackConfigurations(int max, String[] legalTrackTemplatesArray) {
maximumConsecutivePieces = max;
HashSet<TrackConfiguration> temp = new HashSet<TrackConfiguration>();
for (int i = 0; i < legalTrackTemplatesArray.length; i++) {
processTemplate(legalTrackTemplatesArray[i], temp);
}
legalConfigs = new ImHashSet<TrackConfiguration>(temp);
}

getPowerAtDrawbar

Class: jfreerails.world.train.EngineType

Documentation

No documentation available

Source Code

public int getPowerAtDrawbar() {
return powerAtDrawbar;
}

Called Methods

No outgoing method calls

ToAndFroPathIterator

Class: jfreerails.controller.ToAndFroPathIterator

Documentation

No documentation available

Source Code

public ToAndFroPathIterator(List<Point> l) {
list = l;
nextIterator();
}

getSchedule

Class: jfreerails.client.view.TrainOrdersListModel

Documentation

No documentation available

Source Code

private Schedule getSchedule() {
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
trainNumber);
ImmutableSchedule sched = null;
if (train != null) {
sched = (ImmutableSchedule) w.get(principal, KEY.TRAIN_SCHEDULES, train
.getScheduleID());
}
return sched;
}

createMainMap

Class: jfreerails.client.top.GUIComponentFactory

Documentation

No documentation available

Source Code

JScrollPane createMainMap();

Called Methods

No outgoing method calls

main

Class: jfreerails.client.top.ClientJFrame

Documentation

No documentation available

Source Code

public static void main(String args[]) {
new ClientJFrame(new GUIComponentFactoryTestImpl()).setVisible(true);
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.controller.OpenListEntry

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof OpenListEntry))
return false;
final OpenListEntry openListEntry = (OpenListEntry) o;
if (f != openListEntry.f)
return false;
if (node != openListEntry.node)
return false;
return true;
}

Called Methods

No outgoing method calls

getLocalPort

Class: jfreerails.network.InetConnectionAccepter

Documentation

No documentation available

Source Code

public int getLocalPort() {
return serverSocket.getLocalPort();
}

Called Methods

No outgoing method calls

getDistance

Class: jfreerails.world.train.TrainMotion

Documentation

/**
* Returns the train's distance along the track from the point the train was
* at at time <code>getStart()</code> at the specified time.
*
* @param t
* the time.
* @return the distance
* @throws IllegalArgumentException
* if t is outside the interval
*/

Source Code

/**
* Returns the train's distance along the track from the point the train was
* at at time <code>getStart()</code> at the specified time.
*
* @param t
* the time.
* @return the distance
* @throws IllegalArgumentException
* if t is outside the interval
*/
public double getDistance(double t) {
checkT(t);
t = Math.min(t, speeds.getT());
return speeds.calcS(t);
}

gotoIndex

Class: jfreerails.world.top.WorldIterator

Documentation

/**
* Moves the cursor to the specified index.
*
* @throws NoSuchElementException
* if index out of range
*/

Source Code

/**
* Moves the cursor to the specified index.
*
* @throws NoSuchElementException
* if index out of range
*/
void gotoIndex(int i);

Called Methods

No outgoing method calls

send2AllExcept

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

/** Sends the specified message to all connections except the specified one. */

Source Code

/** Sends the specified message to all connections except the specified one. */
private void send2AllExcept(Connection2Client dontSend2,
FreerailsSerializable message) {
Iterator<NameAndPassword> it = acceptedConnections.keySet().iterator();
while (it.hasNext()) {
NameAndPassword p = it.next();
Connection2Client connection = acceptedConnections.get(p);
if (dontSend2 != connection) {
try {
connection.writeToClient(message);
connection.flush();
} catch (Exception e) {
if (connection.isOpen()) {
e.printStackTrace();
try {
removeConnection(p);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
}

finished

Class: jfreerails.util.FreerailsProgressMonitor

Documentation

No documentation available

Source Code

void finished();

Called Methods

No outgoing method calls

StationNamesRenderer

Class: jfreerails.client.renderer.StationNamesRenderer

Documentation

No documentation available

Source Code

public StationNamesRenderer(ReadOnlyWorld world, ModelRoot modelRoot) {
this.w = world;
this.modelRoot = modelRoot;
this.fontSize = 10;
this.bgColor = Color.BLACK;
this.textColor = Color.WHITE;
font = new Font("Arial", 0, fontSize);
}

Called Methods

No outgoing method calls

findTrainIncome

Class: jfreerails.client.view.TrainSummaryJPanel

Documentation

No documentation available

Source Code

private String findTrainIncome(int trainNum) {
IncomeStatementGenerator income = new IncomeStatementGenerator(w,
principal);
Money m = income.calTrainRevenue(trainNum);
return "$" + m.toString();
}

getLastTickTime

Class: jfreerails.network.specifics.MoveChainFork

Documentation

No documentation available

Source Code

public long getLastTickTime() {
return lastTickTime;
}

Called Methods

No outgoing method calls

MovePrecommitter

Class: jfreerails.network.specifics.MovePrecommitter

Documentation

No documentation available

Source Code

MovePrecommitter(World w) {
this.w = w;
}

Called Methods

No outgoing method calls

getType

Class: jfreerails.world.accounts.AddItemTransaction

Documentation

No documentation available

Source Code

public int getType() {
return type;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.controller.PreMoveStatus

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof PreMoveStatus))
return false;
final PreMoveStatus preMoveStatus = (PreMoveStatus) o;
if (!ms.equals(preMoveStatus.ms))
return false;
return true;
}

testReversePath

Class: jfreerails.world.train.TrainPositionOnMapTest

Documentation

No documentation available

Source Code

public void testReversePath() {
TrainPositionOnMap a;
a = TrainPositionOnMap.createInstance(new int[] { 40, 30, 20, 10 },
new int[] { 44, 33, 22, 11 });
FreerailsPathIterator path = a.reversePath();
IntLine line = new IntLine();
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(10, 11, 20, 22));
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(20, 22, 30, 33));
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(30, 33, 40, 44));
assertTrue(!path.hasNext());
}

testStops6

Class: jfreerails.controller.MoveTrainPreMove2ndTest

Documentation

/** Test that a waiting train whose orders change behaves correctly. */

Source Code

/** Test that a waiting train whose orders change behaves correctly. */
public void testStops6() {
PositionOnTrack pot;
TrainMotion tm;
putTrainAtStationWaiting4FullLoad();
// Now change the train's orders.
ImInts newConsist = new ImInts(0, 0);
TrainOrdersModel order0 = new TrainOrdersModel(2, newConsist, false, false);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
MutableSchedule schedule = new MutableSchedule(ta.getSchedule());
schedule.setOrder(0, order0);
ImmutableSchedule imSchedule = schedule.toImmutableSchedule();
world.set(principal, KEY.TRAIN_SCHEDULES, 0, imSchedule);
assertEquals(0, ta.getSchedule().getOrderToGoto());
assertFalse(ta.getSchedule().getOrder(0).waitUntilFull);
// Then the train should continue.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station2Location.x - 1, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
}

remove

Class: jfreerails.util.ArrayBase

Documentation

/**
* Remove a range of value from the array. The index positions for values
* above the range removed are decreased by the number of values removed.
*
* @param from
* index number of first value to be removed
* @param to
* index number past last value to be removed
*/

Source Code

/**
* Remove a range of value from the array. The index positions for values
* above the range removed are decreased by the number of values removed.
*
* @param from
* index number of first value to be removed
* @param to
* index number past last value to be removed
*/
public void remove(int from, int to) {
if (from >= 0 && to <= countPresent && from <= to) {
if (to < countPresent) {
int change = from - to;
Object base = getArray();
System.arraycopy(base, to, base, from, countPresent - to);
discardValues(countPresent + change, countPresent);
countPresent += change;
}
} else {
throw new ArrayIndexOutOfBoundsException("Invalid remove range");
}
}

createBufferStrategy

Class: jfreerails.controller.ScreenHandler

Documentation

No documentation available

Source Code

private synchronized void createBufferStrategy() {
// Use 2 backbuffers to avoid using too much VRAM.
frame.createBufferStrategy(2);
bufferStrategy = frame.getBufferStrategy();
setRepaintOffAndDisableDoubleBuffering(frame);
}

PreMoveAndMove

Class: jfreerails.network.specifics.PreMoveAndMove

Documentation

No documentation available

Source Code

PreMoveAndMove(PreMove preMove, Move move) {
m = move;
pm = preMove;
}

Called Methods

No outgoing method calls

clone

Class: jfreerails.util.IntArray

Documentation

/**
* Duplicates the object with the generic call.
*
* @return a copy of the object
*/

Source Code

/**
* Duplicates the object with the generic call.
*
* @return a copy of the object
*/
@Override
public Object clone() {
return new IntArray(this);
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.world.common.Step

Documentation

/**
* Returns the name of the vector. E.g. "north-east"
*
* @return the name.
*/

Source Code

/**
* Returns the name of the vector. E.g. "north-east"
*
* @return the name.
*/
@Override
public String toString() {
String name;
switch (deltaY) {
case 1:
name = " south";
break;
case -1:
name = " north";
break;
default:
name = "";
break;
}
switch (deltaX) {
case 1:
name += " east";
break;
case -1:
name += " west";
break;
default:
break;
}
return name;
}

Called Methods

No outgoing method calls

generateOverheadFilename

Class: jfreerails.client.renderer.TrainImages

Documentation

No documentation available

Source Code

public static String generateOverheadFilename(String name, int i) {
Step[] vectors = Step.getList();
return "trains" + File.separator + "overhead" + File.separator + name
+ "_" + vectors[i].toAbrvString() + ".png";
}

absolute2relativeTime

Class: jfreerails.world.common.ActivityIterator

Documentation

/**
* Converts an absolute time value to a time value relative to the start of
* the current activity. If absoluteTime > getFinishTime(), getDuration() is
* returned.
*/

Source Code

/**
* Converts an absolute time value to a time value relative to the start of
* the current activity. If absoluteTime > getFinishTime(), getDuration() is
* returned.
*/
double absolute2relativeTime(double absoluteTime);

Called Methods

No outgoing method calls

ImPoint

Class: jfreerails.world.common.ImPoint

Documentation

No documentation available

Source Code

public ImPoint(int x, int y) {
this.x = x;
this.y = y;
}

Called Methods

No outgoing method calls

end_TrackSet

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void end_TrackSet() throws SAXException {
}

Called Methods

No outgoing method calls

hasNextInt

Class: jfreerails.controller.TrainPathIntIterator

Documentation

No documentation available

Source Code

public boolean hasNextInt() {
return trackExplorer.hasNextEdge();
}

createBrokerMenu

Class: experimental.SimpleComponentFactoryImpl2

Documentation

No documentation available

Source Code

public JMenu createBrokerMenu() {
JMenu brokerMenu = new JMenu("Broker");
return brokerMenu;
}

Called Methods

No outgoing method calls

paintComponent

Class: jfreerails.client.view.LoadGameJPanel

Documentation

No documentation available

Source Code

@Override
protected void paintComponent(Graphics g) {
ImStringList files = (ImStringList) modelRoot.getProperty(Property.SAVED_GAMES_LIST);
if(!lastFiles.equals(files)){
updateListOfFiles();
}
super.paintComponent(g);
}

changeSign

Class: jfreerails.world.common.Money

Documentation

No documentation available

Source Code

public Money changeSign() {
return new Money(-amount);
}

Called Methods

No outgoing method calls

getSaveGameNames

Class: jfreerails.server.SavedGamesManagerImpl

Documentation

No documentation available

Source Code

public String[] getSaveGameNames() {
java.io.File dir = new File("./");
FilenameFilter filter = new SavFileFilter();
String[] files = dir.list(filter);
return files;
}

Called Methods

No outgoing method calls

getWorld

Class: jfreerails.world.top.MapFixtureFactory

Documentation

/**
* Returns a world object with a map of the specified size with the terrain
* and cargo types setup.
*/

Source Code

/**
* Returns a world object with a map of the specified size with the terrain
* and cargo types setup.
*/
public static World getWorld(int w, int h) {
FreerailsTile tile = FreerailsTile.getInstance(0);
World world = new WorldImpl(w, h);
generateTerrainTypesList(world);
generateCargoTypesList(world);
for (int x = 0; x < w; x++) {
for (int y = 0; y < w; y++) {
world.setTile(x, y, tile);
}
}
return world;
}

createInSameDirectionAsPath

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public static TrainPositionOnMap createInSameDirectionAsPath(
FreerailsPathIterator path, double speed, double acceleration,
SpeedTimeAndStatus.TrainActivity activity) {
IntArray xPointsIntArray = new IntArray();
IntArray yPointsIntArray = new IntArray();
IntLine line = new IntLine();
int i = 0;
while (path.hasNext()) {
path.nextSegment(line);
xPointsIntArray.add(i, line.x1);
yPointsIntArray.add(i, line.y1);
i++;
if (i > 10000) {
throw new IllegalStateException(
"The TrainPosition has more than 10,000 points, which suggests that something is wrong.");
}
}
xPointsIntArray.add(i, line.x2);
yPointsIntArray.add(i, line.y2);
int[] xPoints;
int[] yPoints;
xPoints = xPointsIntArray.toArray();
yPoints = yPointsIntArray.toArray();
return new TrainPositionOnMap(xPoints, yPoints, speed, acceleration,
activity);
}

setup

Class: jfreerails.client.view.NewsPaperJPanel

Documentation

No documentation available

Source Code

public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
this.callBack = closeAction;
}

Called Methods

No outgoing method calls

getCategory

Class: jfreerails.world.train.WagonType

Documentation

No documentation available

Source Code

public int getCategory() {
return typeCategory;
}

Called Methods

No outgoing method calls

testRemoveFromTail

Class: jfreerails.world.train.TrainPositionOnMapTest

Documentation

No documentation available

Source Code

public void testRemoveFromTail() {
TrainPositionOnMap a;
TrainPositionOnMap c;
TrainPositionOnMap e;
TrainPositionOnMap f;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20, 40, 50, 60 },
new int[] { 11, 22, 44, 55, 66 });
c = TrainPositionOnMap.createInstance(new int[] { 48, 50, 60 },
new int[] { 49, 55, 66 });
e = TrainPositionOnMap.createInstance(new int[] { 10, 20, 40, 48 },
new int[] { 11, 22, 44, 49 });
f = a.removeFromTail(c);
assertEquals(e, f);
}

Demand4Cargo

Class: jfreerails.world.station.Demand4Cargo

Documentation

No documentation available

Source Code

public Demand4Cargo(boolean[] demandArray) {
demand = ImInts.fromBoolean(demandArray);
}

markCompletelyClean

Class: jfreerails.client.common.RepaintManagerForActiveRendering

Documentation

No documentation available

Source Code

@Override
public void markCompletelyClean(JComponent aComponent) {
if (hasDifferentAncestor(aComponent)) {
super.markCompletelyClean(aComponent);
} else {
numRepaintRequests++;
}
}

write

Class: jfreerails.network.SynchronizedQueue

Documentation

No documentation available

Source Code

public synchronized void write(FreerailsSerializable f) {
queue.add(f);
}

Called Methods

No outgoing method calls

ImmutableCargoBundle

Class: jfreerails.world.cargo.ImmutableCargoBundle

Documentation

No documentation available

Source Code

public ImmutableCargoBundle(SortedMap<CargoBatch, Integer> sortedMap) {
int size = sortedMap.size();
int[] amountsArray = new int[size];
CargoBatch[] batchesArray = new CargoBatch[size];
int i = 0;
for (CargoBatch batch : sortedMap.keySet()) {
batchesArray[i] = batch;
amountsArray[i] = sortedMap.get(batch);
i++;
}
batches = new ImList<CargoBatch>(batchesArray);
amounts = new ImInts(amountsArray);
}

Called Methods

No outgoing method calls

InetConnection2Client

Class: jfreerails.network.InetConnection2Client

Documentation

No documentation available

Source Code

public InetConnection2Client(Socket s) throws IOException {
super(s);
}

testStackingOfActivities

Class: jfreerails.move.NextActivityMoveTest

Documentation

No documentation available

Source Code

public void testStackingOfActivities() {
World w = getWorld();
FreerailsPrincipal principal = getPrincipal();
Activity act = new WorldImplTest.TestActivity(50);
w.addActiveEntity(principal, act);
Activity act2 = new WorldImplTest.TestActivity(60);
Move move = new NextActivityMove(act2, 0,
principal);
assertDoMoveIsOk(move);
GameTime currentTime = new GameTime(0);
assertEquals(currentTime, w.currentTime());
ActivityIterator it = w.getActivities(principal, 0);
assertEquals(it.getActivity(), act);
assertEquals(it.getStartTime(), currentTime.getTicks(), 0.00001);
assertEquals(50d, it.getDuration(), 0.00001);
assertEquals(50d, it.getFinishTime(), 0.00001);
assertTrue(it.hasNext());
it.nextActivity();
assertEquals(it.getActivity(), act2);
assertEquals(50, it.getStartTime(), 0.00001);
assertEquals(60, it.getDuration(), 0.0001d);
assertEquals(110, it.getFinishTime(), 0.00001);
}

generateRules

Class: jfreerails.controller.BuildTrackStrategy

Documentation

No documentation available

Source Code

private static int[] generateRules(ArrayList<Integer> allowable,
ReadOnlyWorld w) {
int noTerrainTypes = w.size(SKEY.TERRAIN_TYPES);
int[] newRules = new int[noTerrainTypes];
for (int i = 0; i < noTerrainTypes; i++) {
TerrainType terrainType = (TerrainType) w
.get(SKEY.TERRAIN_TYPES, i);
newRules[i] = -1; // the default value.
for (Integer rule : allowable) {
if (null != rule) {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES,
rule.intValue());
if (trackRule.canBuildOnThisTerrainType(terrainType
.getCategory())) {
newRules[i] = rule.intValue();
break;
}
}
}
}
return newRules;
}

mouseEntered

Class: jfreerails.client.view.StationPlacementCursor

Documentation

No documentation available

Source Code

@Override
public void mouseEntered(MouseEvent e) {
stationRadiusRenderer.show();
}

testMove

Class: jfreerails.move.ChangeCargoBundleMoveTest

Documentation

No documentation available

Source Code

@Override
public void testMove() {
MutableCargoBundle before;
MutableCargoBundle after;
before = new MutableCargoBundle();
after = new MutableCargoBundle();
before.setAmount(new CargoBatch(1, 2, 3, 4, 0), 5);
after.setAmount(new CargoBatch(1, 2, 3, 4, 0), 8);
Move m = new ChangeCargoBundleMove(before.toImmutableCargoBundle(),
after.toImmutableCargoBundle(), 0,
MapFixtureFactory.TEST_PRINCIPAL);
assertSurvivesSerialisation(m);
assertTryMoveFails(m);
assertTryUndoMoveFails(m);
getWorld().add(MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES,
before.toImmutableCargoBundle());
}

getInstance

Class: jfreerails.client.renderer.ZoomedOutMapRenderer

Documentation

No documentation available

Source Code

public static ZoomedOutMapRenderer getInstance(ReadOnlyWorld world,
Dimension maxSize) {
// Work with doubles to avoid rounding errors.
double worldWidth = world.getMapWidth();
double worldHeight = world.getMapHeight();
double scale;
if (worldWidth / worldHeight > maxSize.getWidth() / maxSize.getHeight()) {
scale = maxSize.getWidth() / worldWidth;
} else {
scale = maxSize.getHeight() / worldHeight;
}
double height = scale * worldHeight;
double width = scale * worldWidth;
return new ZoomedOutMapRenderer(world, (int) width, (int) height, 0, 0,
world.getMapWidth(), world.getMapHeight());
}

validateInput

Class: jfreerails.launcher.SelectMapJPanel

Documentation

No documentation available

Source Code

public boolean validateInput() {
/* Validate map selection. */
if (this.getSelection().equals(Selection.NONE)) {
owner.setInfoText(SELECT_A_MAP, LauncherInterface.ERROR);
return false;
}
/* Validate port. */
try {
int port = getServerPort();
if (port < 0 || port > 65535) {
owner.setInfoText(INVALID_PORT, LauncherInterface.ERROR);
return false;
}
} catch (Exception e) {
owner.setInfoText(INVALID_PORT, LauncherInterface.ERROR);
return false;
}
/* Everything is ok. */
owner.hideErrorMessages();
owner.setProperty("freerails.server.port", this.serverPort.getText());
owner.saveProps();
return true;
}

getNewMapNames

Class: jfreerails.server.SavedGamesManagerImpl

Documentation

No documentation available

Source Code

public String[] getNewMapNames() {
return NewGameMessage2Server.getMapNames();
}

getStationY

Class: jfreerails.world.station.StationModel

Documentation

No documentation available

Source Code

public int getStationY() {
return y;
}

Called Methods

No outgoing method calls

run

Class: jfreerails.network.EchoGameServer

Documentation

No documentation available

Source Code

public void run() {
status.open();
while (status.isOpen()) {
update();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// do nothing.
}
}
}

tryDoMove

Class: jfreerails.move.AddPlayerMove

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (isAlreadyASimilarPlayer(w))
return MoveStatus
.moveFailed("There is already a player with the same name.");
return MoveStatus.MOVE_OK;
}

isDiagonal

Class: jfreerails.world.common.Step

Documentation

No documentation available

Source Code

public boolean isDiagonal() {
return 0 != deltaX * deltaY;
}

Called Methods

No outgoing method calls

testPath

Class: jfreerails.world.train.TrainPositionOnMapTest

Documentation

No documentation available

Source Code

public void testPath() {
TrainPositionOnMap a;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20, 30, 40 },
new int[] { 11, 22, 33, 44 });
FreerailsPathIterator path = a.path();
IntLine line = new IntLine();
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(10, 11, 20, 22));
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(20, 22, 30, 33));
assertTrue(path.hasNext());
path.nextSegment(line);
assertEquals(line, new IntLine(30, 33, 40, 44));
assertTrue(!path.hasNext());
}

okButtonActionPerformed

Class: jfreerails.client.view.LoadGameJPanel

Documentation

No documentation available

Source Code

private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
String filename = (String)jList1.getSelectedValue();
Message2Server message2 = new LoadGameMessage2Server(1,
filename);
modelRoot.sendCommand(message2);
if(null != close)
close.actionPerformed(evt);
}//GEN-LAST:event_okButtonActionPerformed

setY

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

public void setY(int y) {
this.y = y;
}

Called Methods

No outgoing method calls

processingInstruction

Class: jfreerails.server.parser.CargoAndTerrainParser

Documentation

/**
* This SAX interface method is implemented by the parser.
*
*/

Source Code

/**
* This SAX interface method is implemented by the parser.
*
*/
public final void processingInstruction(java.lang.String target,
java.lang.String data) throws SAXException {
}

Called Methods

No outgoing method calls

processTemplate

Class: jfreerails.world.track.LegalTrackConfigurations

Documentation

No documentation available

Source Code

static private void processTemplate(String trackTemplateString,
HashSet<TrackConfiguration> temp) {
int trackTemplate = Integer.parseInt(trackTemplateString, 2);
// Check for invalid parameters.
if ((trackTemplate > 511) || (trackTemplate < 0)) {
throw new IllegalArgumentException("trackTemplate = "
+ trackTemplate + ", it should be in the range 0-511");
}
int[] rotationsOfTrackTemplate = EightRotationsOfTrackPieceProducer
.getRotations(trackTemplate);
for (int k = 0; k < rotationsOfTrackTemplate.length; k++) {
int i = rotationsOfTrackTemplate[k];
TrackConfiguration trackConfiguration = TrackConfiguration
.from9bitTemplate(i);
if (!temp.contains(trackConfiguration)) {
temp.add(trackConfiguration);
}
}
}

getConversion

Class: jfreerails.world.terrain.NullTerrainType

Documentation

No documentation available

Source Code

public ImList<Conversion> getConversion() {
return new ImList<Conversion>();
}

Called Methods

No outgoing method calls

getImage

Class: jfreerails.client.top.RenderersRootImpl

Documentation

No documentation available

Source Code

public Image getImage(String relativeFilename) throws IOException {
return imageManager.getImage(relativeFilename);
}

paintTrainHighlight

Class: jfreerails.client.renderer.TrainRenderer

Documentation

No documentation available

Source Code

public void paintTrainHighlight(Graphics g, TrainModel train, List<Entry<Point, Step>> positions, TrainImages.Highlight highlight) {
for (int i = 0; i < positions.size(); i++) {
TrainImages trainImages;
if (i == 0) {
trainImages = rr.getEngineImages(train.getEngineType());
} else {
int type = train.getWagon(i - 1);
trainImages = rr.getWagonImages(type);
}
Entry<Point, Step> entry = positions.get(i);
Image image = trainImages.getOverheadHighlightImage(entry.getValue().getID(), highlight);
Point p = entry.getKey();
g.drawImage(image, p.x - 15, p.y - 15, null);
}
}

addPlayer

Class: jfreerails.world.top.WorldImpl

Documentation

/**
* @param player
* Player to add
* @return index of the player
*/

Source Code

/**
* @param player
* Player to add
* @return index of the player
*/
public int addPlayer(Player player) {
if (null == player) {
throw new NullPointerException();
}
int index = players.add(player);
bankAccounts.addD1();
currentBalance.add(new Money(0));
lists.addD1();
for (int i = 0; i < KEY.getNumberOfKeys(); i++) {
lists.addD2(index);
}
activityLists.addD1();
return index;
}

IntLineTest

Class: jfreerails.world.train.IntLineTest

Documentation

No documentation available

Source Code

public IntLineTest(String arg0) {
super(arg0);
}

Called Methods

No outgoing method calls

testBinaryFormat

Class: jfreerails.client.common.BinaryNumberFormatterTest

Documentation

No documentation available

Source Code

public void testBinaryFormat() {
assertEquals("0", BinaryNumberFormatter.format(0, 1));
assertEquals("1", BinaryNumberFormatter.format(1, 1));
assertEquals("00", BinaryNumberFormatter.format(0, 2));
assertEquals("01", BinaryNumberFormatter.format(1, 2));
assertEquals("10", BinaryNumberFormatter.format(2, 2));
assertEquals("11", BinaryNumberFormatter.format(3, 2));
assertEquals("1111", BinaryNumberFormatter.format(15, 4));
try {
BinaryNumberFormatter.format(-1, 2);
assertTrue(false);
} catch (IllegalArgumentException e) {
}
try {
BinaryNumberFormatter.format(4, 2);
assertTrue(false);
} catch (IllegalArgumentException e) {
}
}

equals

Class: jfreerails.world.accounts.Receipt

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof Receipt) {
Receipt test = (Receipt) o;
return test.amount.equals(amount) && category == test.category;
}
return false;
}

addListListener

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public void addListListener(WorldListListener listener) {
this.moveFork.addListListener(listener);
}

preloadSounds

Class: jfreerails.client.top.RenderersRootImpl

Documentation

No documentation available

Source Code

private void preloadSounds(FreerailsProgressMonitor pm) {
// Pre-load sounds..
String[] soundsFiles = { "/jfreerails/client/sounds/buildtrack.wav",
"/jfreerails/client/sounds/cash.wav",
"/jfreerails/client/sounds/removetrack.wav",
"/jfreerails/client/sounds/whistle.wav" };
pm.nextStep(soundsFiles.length);
SoundManager sm = SoundManager.getSoundManager();
for (int i = 0; i < soundsFiles.length; i++) {
try {
sm.addClip(soundsFiles[i]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedAudioFileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pm.setValue(i + 1);
}
}

size

Class: jfreerails.world.common.ImStringList

Documentation

No documentation available

Source Code

public int size() {
return strings.length;
}

Called Methods

No outgoing method calls

mustConnectToExistingTrack

Class: jfreerails.move.ChangeTrackPieceCompositeMove

Documentation

No documentation available

Source Code

private static boolean mustConnectToExistingTrack(ReadOnlyWorld world) {
GameRules rules = (GameRules) world.get(ITEM.GAME_RULES);
return rules.isMustConnect2ExistingTrack();
}

hashCode

Class: jfreerails.world.train.CompositeSpeedAgainstTime

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
long temp;
result = values.hashCode();
temp = finalT != +0.0d ? Double.doubleToLongBits(finalT) : 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
temp = finalS != +0.0d ? Double.doubleToLongBits(finalS)
: 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
return result;
}

getCategory

Class: jfreerails.world.accounts.Receipt

Documentation

No documentation available

Source Code

public Category getCategory() {
return category;
}

Called Methods

No outgoing method calls

ChangeTrackPieceMoveTest

Class: jfreerails.move.ChangeTrackPieceMoveTest

Documentation

No documentation available

Source Code

public ChangeTrackPieceMoveTest(String testName) {
super(testName);
}

uGet

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

@Override
T uGet(int... i) {
if (i.length != 3)
throw new IllegalArgumentException();
return underlyingList.get(i[0], i[1], i[2]);
}

testStops5

Class: jfreerails.controller.MoveTrainPreMove2ndTest

Documentation

/**
* Test that when the train <b>is</b> scheduled to wait for full load, it
* waits.
*/

Source Code

/**
* Test that when the train <b>is</b> scheduled to wait for full load, it
* waits.
*/
public void testStops5() {
PositionOnTrack pot;
TrainMotion tm;
putTrainAtStationWaiting4FullLoad();
// Add enough cargo to fill up the train.
addCargoAtStation(2, 70);
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station2Location.x - 1, pot.getX());
assertEquals(station2Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
}

paintComponent

Class: experimental.TrainMotionExpt

Documentation

No documentation available

Source Code

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Shade tiles with track..
g.setColor(Color.GREEN);
for (int x = 0; x < world.getMapWidth(); x++) {
for (int y = 0; y < world.getMapHeight(); y++) {
FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
if (tile.getTrackPiece().getTrackTypeID() != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
int w = Step.TILE_DIAMETER;
int h = Step.TILE_DIAMETER;
g.drawRect(x * Step.TILE_DIAMETER, y * Step.TILE_DIAMETER,
w, h);
}
}
}
long l = System.currentTimeMillis() - startTime;
double ticks = (double) l / 1000;
while (ticks > finishTime) {
updateTrainPosition();
}
ActivityIterator ai = world.getActivities(principal, 0);
while (ai.getFinishTime() < ticks && ai.hasNext()) {
ai.nextActivity();
}
double t = Math.min(ticks, ai.getFinishTime());
t = t - ai.getStartTime();
TrainMotion motion = (TrainMotion) ai.getActivity();
TrainPositionOnMap pos = (TrainPositionOnMap) ai.getState(ticks);
PathOnTiles pathOT = motion.getPath();
Iterator<ImPoint> it = pathOT.tiles();
while (it.hasNext()) {
ImPoint tile = it.next();
int x = tile.x * Step.TILE_DIAMETER;
int y = tile.y * Step.TILE_DIAMETER;
int w = Step.TILE_DIAMETER;
int h = Step.TILE_DIAMETER;
g.setColor(Color.WHITE);
g.fillRect(x, y, w, h);
g.setColor(Color.DARK_GRAY);
g.drawRect(x, y, w, h);
}
pathOT = motion.getTiles(t);
it = pathOT.tiles();
while (it.hasNext()) {
ImPoint tile = it.next();
int x = tile.x * Step.TILE_DIAMETER;
int y = tile.y * Step.TILE_DIAMETER;
int w = Step.TILE_DIAMETER;
int h = Step.TILE_DIAMETER;
g.setColor(Color.LIGHT_GRAY);
g.fillRect(x, y, w, h);
g.setColor(Color.DARK_GRAY);
g.drawRect(x, y, w, h);
}
g.setColor(Color.BLACK);
IntLine line = new IntLine();
FreerailsPathIterator path = pos.path();
while (path.hasNext()) {
path.nextSegment(line);
g.drawLine(line.x1, line.y1, line.x2, line.y2);
}
int speed = (int) Math.round(pos.getSpeed());
g.drawString("Speed: " + speed, 260, 60);
}

BuildTrainDialogAction

Class: jfreerails.client.view.BuildTrainDialogAction

Documentation

No documentation available

Source Code

public BuildTrainDialogAction() {
super("Build Train");
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0));
putValue(SHORT_DESCRIPTION, "Build a new train");
}

Called Methods

No outgoing method calls

mouseMoved

Class: jfreerails.client.view.MainMapAndOverviewMapMediator

Documentation

No documentation available

Source Code

@Override
public void mouseMoved(MouseEvent evt) {
lastMouseLocation.x = evt.getX();
lastMouseLocation.y = evt.getY();
updateInside(evt);
}

checkStationExists

Class: jfreerails.controller.VerifyStationName

Documentation

No documentation available

Source Code

private boolean checkStationExists(String name) {
String testName = name;
StationModel tempStation;
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
while (wi.next()) { // loop over non null stations
tempStation = (StationModel) wi.getElement();
if ((testName).equals(tempStation.getStationName())) {
// station already exists with that name
return true;
}
}
}
// no stations exist with that name
return false;
}

isOpen

Class: jfreerails.network.Connection2Client

Documentation

/** Returns true if this connection is open. */

Source Code

/** Returns true if this connection is open. */
boolean isOpen();

Called Methods

No outgoing method calls

hasNextEdge

Class: jfreerails.controller.Map

Documentation

No documentation available

Source Code

public boolean hasNextEdge() {
if (nodes[position].edges.length > (branch + 1)) {
return true;
}
return false;
}

Called Methods

No outgoing method calls

updateHtml

Class: jfreerails.client.view.BalanceSheetHtmlJPanel

Documentation

No documentation available

Source Code

private void updateHtml() {
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
BalanceSheetGenerator balanceSheetGenerator = new BalanceSheetGenerator(
world, playerPrincipal);
String populatedTemplate = populateTokens(template,
balanceSheetGenerator);
setHtml(populatedTemplate);
}

growArray

Class: jfreerails.util.GrowableBase

Documentation

/**
* Increase the size of the array to at least a specified size. The array
* will normally be at least doubled in size, but if a maximum size
* increment was specified in the constructor and the value is less than the
* current size of the array, the maximum increment will be used instead. If
* the requested size requires more than the default growth, the requested
* size overrides the normal growth and determines the size of the
* replacement array.
*
* @param required
* new minimum size required
*/

Source Code

/**
* Increase the size of the array to at least a specified size. The array
* will normally be at least doubled in size, but if a maximum size
* increment was specified in the constructor and the value is less than the
* current size of the array, the maximum increment will be used instead. If
* the requested size requires more than the default growth, the requested
* size overrides the normal growth and determines the size of the
* replacement array.
*
* @param required
* new minimum size required
*/
protected void growArray(int required) {
Object base = getArray();
int size = Math.max(required, countLimit
+ Math.min(countLimit, maximumGrowth));
Class type = base.getClass().getComponentType();
Object grown = Array.newInstance(type, size);
resizeCopy(base, grown);
countLimit = size;
setArray(grown);
}

List2DDiff

Class: jfreerails.util.List2DDiff

Documentation

No documentation available

Source Code

public List2DDiff(SortedMap<ListKey, Object> diffs, List2D<T> list,
Enum listID) {
super(diffs, listID);
underlyingList = list;
}

fileNameTextFieldActionPerformed

Class: jfreerails.client.view.SaveGameJPanel

Documentation

No documentation available

Source Code

private void fileNameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileNameTextFieldActionPerformed
// TODO add your handling code here:
System.out.println("fileNameTextFieldActionPerformed"+evt.toString());
}//GEN-LAST:event_fileNameTextFieldActionPerformed

Called Methods

No outgoing method calls

dontWaitJMenuItemActionPerformed

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void dontWaitJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_dontWaitJMenuItemActionPerformed
setWaitUntilFull(false);
}// GEN-LAST:event_dontWaitJMenuItemActionPerformed

canAddWagon

Class: jfreerails.world.train.TrainModel

Documentation

No documentation available

Source Code

public boolean canAddWagon() {
return wagonTypes.size() < MAX_NUMBER_OF_WAGONS;
}

sendMapUpdated

Class: jfreerails.network.specifics.MoveChainFork

Documentation

No documentation available

Source Code

private void sendMapUpdated(Rectangle r) {
for (int i = 0; i < mapListeners.size(); i++) {
WorldMapListener l = mapListeners.get(i);
l.tilesChanged(r);
}
}

setUp

Class: jfreerails.move.ChangeTrackPieceCompositeMoveTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() {
super.setHasSetupBeenCalled(true);
setWorld(new WorldImpl(10, 10));
getWorld().set(ITEM.GAME_RULES, GameRules.DEFAULT_RULES);
getWorld().addPlayer(MapFixtureFactory.TEST_PLAYER);
MapFixtureFactory.generateTrackRuleList(getWorld());
transactionsGenerator = new TrackMoveTransactionsGenerator(getWorld(),
MapFixtureFactory.TEST_PRINCIPAL);
}

ZoomedOutMapRenderer

Class: jfreerails.client.renderer.ZoomedOutMapRenderer

Documentation

No documentation available

Source Code

private ZoomedOutMapRenderer(ReadOnlyWorld world, int width, int height,
int mapX, int mapY, int mapWidth, int mapHeight) {
w = world;
this.mapWidth = mapWidth;
this.mapHeight = mapHeight;
imageHeight = height;
imageWidth = width;
double scalingFactor = ((double) imageHeight) / mapHeight;
affineTransform = AffineTransform.getScaleInstance(scalingFactor,
scalingFactor);
this.mapX = mapX;
this.mapY = mapY;
refresh();
}

equals

Class: jfreerails.world.player.Player

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (!(o instanceof Player)) {
return false;
}
// return (name.equals(((Player) o).name) && keysEqual);
return (name.equals(((Player) o).name));
}

Called Methods

No outgoing method calls

getSaveGameAction

Class: jfreerails.client.view.ServerControlModel

Documentation

/**
* @return an action to save a game TODO The action produces a file selector
* dialog to save the game
*/

Source Code

/**
* @return an action to save a game TODO The action produces a file selector
* dialog to save the game
*/
public Action getSaveGameAction() {
return saveGameAction;
}

Called Methods

No outgoing method calls

createMainMap

Class: experimental.SimpleComponentFactoryImpl2

Documentation

No documentation available

Source Code

public JScrollPane createMainMap() {
if (null == this.mainMap) {
// this.mainMap = new MapJPanel();
this.mainMap = new MapViewJComponentConcrete();
mainMapScrollPane1 = new JScrollPane();
mainMapScrollPane1.setViewportView(this.mainMap);
addMainMapAndOverviewMapMediatorIfNecessary();
}
return mainMapScrollPane1;
}

write

Class: jfreerails.util.FlowRateOutputStream

Documentation

No documentation available

Source Code

@Override
public void write(byte[] b) throws IOException {
super.out.write(b, 0, b.length);
totalByteSent += b.length;
}

Called Methods

No outgoing method calls

refreshSavedGames

Class: jfreerails.controller.ServerControlInterface

Documentation

No documentation available

Source Code

void refreshSavedGames();

Called Methods

No outgoing method calls

getIndex

Class: jfreerails.move.AddItemToListMove

Documentation

No documentation available

Source Code

public int getIndex() {
return index;
}

Called Methods

No outgoing method calls

createParallelLine

Class: experimental.TrackRenderer

Documentation

No documentation available

Source Code

public static Line2D.Double createParallelLine(Line2D.Double line,
double shift) {
Line2D.Double returnValue = new Line2D.Double(line.getP1(), line
.getP2());
double distance = line.getP1().distance(line.getP2());
double dRatio = shift / distance;
double dx = (line.x1 - line.x2) * dRatio;
double dy = (line.y1 - line.y2) * dRatio;
returnValue.x1 -= dy;
returnValue.y1 += dx;
returnValue.x2 -= dy;
returnValue.y2 += dx;
return returnValue;
}

Called Methods

No outgoing method calls

getProperty

Class: jfreerails.network.specifics.FreerailsClient

Documentation

No documentation available

Source Code

public final Serializable getProperty(ClientProperty propertyName) {
return properties.get(propertyName.name());
}

Called Methods

No outgoing method calls

canBuildOnThisTerrainType

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

public boolean canBuildOnThisTerrainType(TerrainType.Category TerrainType) {
return legalTrackPlacement.canBuildOnThisTerrain(TerrainType);
}

write

Class: jfreerails.server.ServerGameModelImpl

Documentation

No documentation available

Source Code

public void write(ObjectOutputStream objectOut) throws IOException {
objectOut.writeObject(world);
objectOut.writeObject(serverAutomata);
/**
* save player private data
*/
for (int i = 0; i < world.getNumberOfPlayers(); i++) {
Player player = world.getPlayer(i);
player.saveSession(objectOut);
}
}

getSaveGameNames

Class: jfreerails.network.specifics.SavedGamesManager

Documentation

No documentation available

Source Code

String[] getSaveGameNames();

Called Methods

No outgoing method calls

moveCursorMoreTiles

Class: jfreerails.client.renderer.BuildTrackController

Documentation

/**
* uses <code>trackBuilder</code> if not null -- otherwise uses own
* <code>buildTrack</code> method - that is applied on
* <code>worldDifferences</code>
*
* @param track
* List
* @param trackBuilder
* TrackMoveProducer
*/

Source Code

/**
* uses <code>trackBuilder</code> if not null -- otherwise uses own
* <code>buildTrack</code> method - that is applied on
* <code>worldDifferences</code>
*
* @param track
* List
* @param trackBuilder
* TrackMoveProducer
*/
private MoveStatus moveCursorMoreTiles(List<ImPoint> track,
TrackMoveProducer trackBuilder) {
ImPoint oldPosition = getCursorPosition();
if(!Step.checkValidity(oldPosition, track.get(0))){
throw new IllegalStateException(oldPosition.toString()+ " and "+track.get(0).toString());
}
MoveStatus ms = null;
int piecesOfNewTrack = 0;
if (null != trackBuilder) {
trackBuilder.setBuildTrackStrategy(getBts());
}
for (Iterator<ImPoint> iter = track.iterator(); iter.hasNext();) {
ImPoint point = iter.next();
LOGGER.fine("point" + point);
LOGGER.fine("oldPosition" + oldPosition);
if (oldPosition.equals(point)) {
LOGGER.fine("(oldPosition.equals(point))" + point);
continue;
}
Step vector = Step.getInstance(point.x - oldPosition.x, point.y
- oldPosition.y);
// If there is already track between the two tiles, do nothing
FreerailsTile tile = (FreerailsTile) realWorld.getTile(
oldPosition.x, oldPosition.y);
if (tile.getTrackPiece().getTrackConfiguration().contains(vector)) {
oldPosition = point;
continue;
}
piecesOfNewTrack++;
if (trackBuilder != null) {
ms = trackBuilder.buildTrack(oldPosition, vector);
} else {
ms = planBuildingTrack(oldPosition, vector);
}
if (ms.ok) {
setCursorMessage("");
} else {
setCursorMessage(ms.message);
reset();
return ms;
}
oldPosition = point;
}
/* Check whether there is already track at every point. */
if (piecesOfNewTrack == 0) {
MoveStatus moveFailed = MoveStatus.moveFailed("Track already here");
setCursorMessage(moveFailed.message);
return moveFailed;
}
isBuildTrackSuccessful = true;
// If track has actually been built, play the build track sound.
if (trackBuilder != null && ms.isOk()) {
if (trackBuilder.getTrackBuilderMode() == BUILD_TRACK) {
this.soundManager.playSound(
"/jfreerails/client/sounds/buildtrack.wav", 0);
}
}
return ms;
}

setDocumentLocator

Class: jfreerails.server.parser.Track_TilesParser

Documentation

No documentation available

Source Code

public void setDocumentLocator(org.xml.sax.Locator locator) {
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.network.specifics.SetWorldMessage2Client

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + world.hashCode();
return result;
}

Called Methods

No outgoing method calls

isPaused

Class: jfreerails.world.common.GameSpeed

Documentation

No documentation available

Source Code

public boolean isPaused(){
return speed < 1;
}

Called Methods

No outgoing method calls

updateObservedRect

Class: jfreerails.client.view.MainMapAndOverviewMapMediator

Documentation

No documentation available

Source Code

private void updateObservedRect() {
Rectangle r = mainMap.getVisibleRect();
// if (!r.equals(this.currentVisRect)) {
// float overviewScale=overviewMapJPanel.getScale();
// float mainMapScale=mainMap.getScale();
int overviewScale = overviewMapJPanel.getPreferredSize().width;
int mainMapScale = mainMap.getWidth();
if (0 != (overviewScale * mainMapScale)) {
// avoid division by zero.
currentVisRect.x = (r.x * overviewScale / mainMapScale);
currentVisRect.y = (r.y * overviewScale / mainMapScale);
currentVisRect.width = (r.width * overviewScale / mainMapScale);
currentVisRect.height = (r.height * overviewScale / mainMapScale);
overviewMapJPanel.repaint();
}
// }
}

Called Methods

No outgoing method calls

reset

Class: jfreerails.world.top.NonNullElements

Documentation

No documentation available

Source Code

public void reset() {
index = -1;
row = -1;
size = -1;
}

Called Methods

No outgoing method calls

showSelectEngine

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showSelectEngine() {
WorldIterator wi = new NonNullElements(KEY.STATIONS, world, modelRoot
.getPrincipal());
if (!wi.next()) {
modelRoot.setProperty(Property.QUICK_MESSAGE, "Can't"
+ " build train since there are no stations");
} else {
showContent(selectEngine);
}
}

controlPoint

Class: experimental.TrackTilesGenerator

Documentation

No documentation available

Source Code

private Point2D.Double controlPoint(Point2D.Double from) {
double weight = 0.3;
double x = from.getX() * weight + 300 * (1 - weight);
double y = from.getY() * weight + 300 * (1 - weight);
return new Point2D.Double(x, y);
}

Called Methods

No outgoing method calls

addMapListener

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public void addMapListener(WorldMapListener l) {
this.moveFork.addMapListener(l);
}

issueStock

Class: jfreerails.world.accounts.StockTransaction

Documentation

No documentation available

Source Code

public static StockTransaction issueStock(int quantity, long pricePerShare) {
Money amount = new Money(pricePerShare * quantity);
return new StockTransaction(quantity, amount);
}

Called Methods

No outgoing method calls

PositionOnTrackTest

Class: jfreerails.world.common.PositionOnTrackTest

Documentation

/**
* Constructor for PositionOnTrackTest.
*
* @param arg0
*/

Source Code

/**
* Constructor for PositionOnTrackTest.
*
* @param arg0
*/
public PositionOnTrackTest(String arg0) {
super(arg0);
}

Called Methods

No outgoing method calls

getStationID

Class: jfreerails.world.train.TrainOrdersModel

Documentation

No documentation available

Source Code

public int getStationID() {
return stationId;
}

Called Methods

No outgoing method calls

paintRectangleOfTiles

Class: jfreerails.client.renderer.TerrainLayer

Documentation

No documentation available

Source Code

private void paintRectangleOfTiles(Graphics g, int x, int y, int width,
int height) {
paintRectangleOfTiles(g, new Rectangle(x, y, width, height));
}

Called Methods

  • jfreerails.client.renderer.MapBackgroundRender.TerrainLayer.paintRectangleOfTiles (external)

getPossibleConfigurationsIterator

Class: jfreerails.world.track.TrackConfiguration

Documentation

No documentation available

Source Code

public Iterator getPossibleConfigurationsIterator() {
return flatTrackConfigurations.iterator();
}

Called Methods

No outgoing method calls

testCanIssueBond

Class: jfreerails.controller.FinancialDataGathererTest

Documentation

No documentation available

Source Code

public void testCanIssueBond() {
FinancialDataGatherer fdg = new FinancialDataGatherer(w, player
.getPrincipal());
assertTrue(fdg.canIssueBond()); // 5%
assertTrue(addBond()); // 6%
assertTrue(addBond()); // 7%
assertFalse(addBond()); // 8% so can't
fdg = new FinancialDataGatherer(w, player.getPrincipal());
assertEquals(8, fdg.nextBondInterestRate());
}

selectTileIcon

Class: jfreerails.client.renderer.ForestStyleTileRenderer

Documentation

No documentation available

Source Code

@Override
public int selectTileIcon(int x, int y, ReadOnlyWorld w) {
int iconNumber = 0;
for (int i = 0; i < 2; i++) {
iconNumber = iconNumber
| checkTile(x + X_LOOK_AT[i], y + Y_LOOK_AT[i], w);
iconNumber = iconNumber << 1;
}
iconNumber = iconNumber >> 1;
return iconNumber;
}

createMainMap

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

public JScrollPane createMainMap() {
return mainMapScrollPane1;
}

Called Methods

No outgoing method calls

testGetNumberOfKeys

Class: jfreerails.world.top.KEYTest

Documentation

No documentation available

Source Code

public void testGetNumberOfKeys() {
// There were 4 keys when a wrote this test,
// but I expect the number to increase.
assertTrue(KEY.getNumberOfKeys() >= 4);
}

Player

Class: jfreerails.world.player.Player

Documentation

/**
* Used by the client to generate a player with a particular name.
*/

Source Code

/**
* Used by the client to generate a player with a particular name.
*/
public Player(String name) {
this.name = name;
KeyPairGenerator kpg;
/* generate our key pair */
try {
kpg = KeyPairGenerator.getInstance("DSA");
kpg.initialize(1024);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}

Called Methods

No outgoing method calls

getWagonsToAdd

Class: jfreerails.world.train.ImmutableSchedule

Documentation

No documentation available

Source Code

public ImInts getWagonsToAdd() {
TrainOrdersModel order = orders.get(getOrderToGoto());
return order.consist;
}

readResolve

Class: jfreerails.world.track.NullTrackPiece

Documentation

No documentation available

Source Code

private Object readResolve() throws ObjectStreamException {
return nullTrackPiece;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.common.IntLine

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (null == o) {
return false;
}
if (o == this) {
return true;
}
if (o instanceof IntLine) {
IntLine line = (IntLine) o;
if (line.x1 == this.x1 && line.x2 == this.x2 && line.y1 == this.y1
&& line.y2 == this.y2) {
return true;
}
return false;
}
return false;
}

Called Methods

No outgoing method calls

getInstance

Class: jfreerails.world.common.Step

Documentation

No documentation available

Source Code

public static Step getInstance(int number) {
return list[number];
}

Called Methods

No outgoing method calls

getState

Class: jfreerails.world.common.Activity

Documentation

No documentation available

Source Code

E getState(double dt);

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof TrackRuleImpl) {
TrackRuleImpl trackRuleImpl = (TrackRuleImpl) o;
boolean propertiesFieldsEqual = this.properties
.equals(trackRuleImpl.getProperties());
boolean legalConfigurationsEqual = this.legalConfigurations
.equals(trackRuleImpl.getLegalConfigurations());
boolean legalTrackPlacementEqual = this.legalTrackPlacement
.equals(trackRuleImpl.getLegalTrackPlacement());
if (propertiesFieldsEqual && legalConfigurationsEqual
&& legalTrackPlacementEqual) {
return true;
}
return false;
}
return false;
}

emptyConversionArray

Class: jfreerails.world.station.ConvertedAtStation

Documentation

No documentation available

Source Code

public static int[] emptyConversionArray(int numberOfCargoTypes) {
int[] convertedTo = new int[numberOfCargoTypes];
for (int i = 0; i < numberOfCargoTypes; i++) {
convertedTo[i] = NOT_CONVERTED;
}
return convertedTo;
}

Called Methods

No outgoing method calls

testAddingTransaction

Class: jfreerails.move.WorldDiffsMoveTest

Documentation

No documentation available

Source Code

public void testAddingTransaction() {
Transaction t1 = new AddItemTransaction(Category.BOND, 1, 1, new Money(
100));
Transaction t2 = new AddItemTransaction(Category.BOND, 2, 2, new Money(
1000));
Transaction t3 = new AddItemTransaction(Category.BOND, 3, 3, new Money(
10000));
world.addTransaction(fp1, t1);
diffs.addTransaction(fp1, t2);
diffs.addTransaction(fp1, t3);
runTests();
}

getNearestVector

Class: jfreerails.world.common.Step

Documentation

/**
* @return the OneTileMoveVector nearest in orientation to the specified dx,
* dy
*/

Source Code

/**
* @return the OneTileMoveVector nearest in orientation to the specified dx,
* dy
*/
public static Step getNearestVector(int dx, int dy) {
if (0 == dx * dy) {
if (dx > 0) {
return EAST;
} else if (dx != 0) {
return WEST;
} else if (dy > 0) {
return SOUTH;
} else {
return NORTH;
}
}
double gradient = dy;
gradient = gradient / dx;
double B = 2;
double A = 0.5;
double C = -2;
double D = -0.5;
if (gradient > B) {
if (dy < 0) {
return NORTH;
}
return SOUTH;
} else if (gradient > A) {
if (dy > 0) {
return SOUTH_EAST;
}
return NORTH_WEST;
} else if (gradient > D) {
if (dx > 0) {
return EAST;
}
return WEST;
} else if (gradient > C) {
if (dx < 0) {
return SOUTH_WEST;
}
return NORTH_EAST;
} else {
if (dy > 0) {
return SOUTH;
}
return NORTH;
}
}

Called Methods

No outgoing method calls

getStationId

Class: jfreerails.server.MapCustomizer

Documentation

/**
* Returns -1 if no station here or the id of the station if one is
* present.
*/

Source Code

/**
* Returns -1 if no station here or the id of the station if one is
* present.
*/
public int getStationId(ImPoint location) {
FreerailsPrincipal principal = w.getPlayer(0).getPrincipal();
FreerailsTile tile = (FreerailsTile) w.getTile(location.x, location.y);
TrackRule trackRule = tile.getTrackPiece().getTrackRule();
if (trackRule.isStation()
&& tile.getTrackPiece().getOwnerID() == w.getID(principal)) {
for (int i = 0; i < w.size(principal, KEY.STATIONS); i++) {
StationModel station = (StationModel) w.get(principal,
KEY.STATIONS, i);
if (null != station && station.getLocation().equals(location)) {
return i;
}
}
throw new IllegalStateException();
} else {
return -1;
}
}

toString

Class: jfreerails.world.top.KEY

Documentation

No documentation available

Source Code

@Override
public String toString() {
return Utils.findConstantFieldName(this);
}

setup

Class: jfreerails.client.top.ClientJFrame

Documentation

No documentation available

Source Code

private void setup(GUIComponentFactory gcf) {
this.gUIComponentFactory = gcf;
initComponents();
gUIComponentFactory.createDateJLabel();
}

getIndex

Class: jfreerails.util.ListKey

Documentation

No documentation available

Source Code

public int[] getIndex() {
return index.clone();
}

Called Methods

  • _Dummy_.__Array__.clone (external)

SaveGameJPanel

Class: jfreerails.client.view.SaveGameJPanel

Documentation

/** Creates new form SaveGameJPanel */

Source Code

/** Creates new form SaveGameJPanel */
public SaveGameJPanel() {
initComponents();
}

createImageFor

Class: jfreerails.client.top.QuickRGBTileRendererList

Documentation

No documentation available

Source Code

public static Image createImageFor(TerrainType t) {
Image image = defaultConfiguration.createCompatibleImage(
Constants.TILE_SIZE, Constants.TILE_SIZE);
Color c = new Color(t.getRGB());
Graphics g = image.getGraphics();
g.setColor(c);
g.fillRect(0, 0, Constants.TILE_SIZE, Constants.TILE_SIZE);
g.dispose();
return image;
}

setValue

Class: jfreerails.launcher.GUIClient

Documentation

No documentation available

Source Code

public void setValue(int i) {
// TODO Auto-generated method stub
}

Called Methods

No outgoing method calls

equal

Class: jfreerails.util.Utils

Documentation

/**
* Returns true if the objects are equal or both null, otherwise returns
* false. Does not throw null pointer exceptions when either of the objects
* is null.
*/

Source Code

/**
* Returns true if the objects are equal or both null, otherwise returns
* false. Does not throw null pointer exceptions when either of the objects
* is null.
*/
public static boolean equal(Object a, Object b) {
if (null == a || null == b) {
return null == a && null == b;
}
return a.equals(b);
}

Called Methods

No outgoing method calls

createInSameDirectionAsPath

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public static TrainPositionOnMap createInSameDirectionAsPath(
FreerailsPathIterator path) {
return createInSameDirectionAsPath(path, 0d, 0d,
SpeedTimeAndStatus.TrainActivity.READY);
}

isCargo2Transfer

Class: jfreerails.controller.DropOffAndPickupCargoMoveGenerator

Documentation

No documentation available

Source Code

public boolean isCargo2Transfer() {
ImInts spaceAvailable = train.spaceAvailable();
int total = 0;
for (int cargoType = 0; cargoType < w.size(SKEY.CARGO_TYPES); cargoType++) {
int quantity = spaceAvailable.get(cargoType);
int amount2transfer = Math.min(quantity, stationAfter
.getAmount(cargoType));
total += amount2transfer;
}
return total > 0;
}

doMove

Class: jfreerails.move.UndoMove

Documentation

No documentation available

Source Code

public MoveStatus doMove(World w, FreerailsPrincipal p) {
return move2undo.undoMove(w, p);
}

AddActiveEntityMove

Class: jfreerails.move.AddActiveEntityMove

Documentation

No documentation available

Source Code

public AddActiveEntityMove(Activity activity, int index,
FreerailsPrincipal principal) {
this.activity = activity;
this.index = index;
this.principal = principal;
}

Called Methods

No outgoing method calls

refreshTile

Class: jfreerails.client.renderer.Unknown

Documentation

No documentation available

Source Code

public void refreshTile(int x, int y) {
}

Called Methods

No outgoing method calls

retrievePath

Class: jfreerails.controller.SimpleAStarPathFinder

Documentation

No documentation available

Source Code

public IntArray retrievePath() {
return path;
}

Called Methods

No outgoing method calls

removeLastTransaction

Class: jfreerails.world.top.World

Documentation

/**
* Removes and returns the last transaction added the the specified
* principal's bank account. This method is only here so that moves that add
* transactions can be undone.
*/

Source Code

/**
* Removes and returns the last transaction added the the specified
* principal's bank account. This method is only here so that moves that add
* transactions can be undone.
*/
Transaction removeLastTransaction(FreerailsPrincipal p);

Called Methods

No outgoing method calls

jList1ValueChanged

Class: jfreerails.client.view.SelectEngineJPanel

Documentation

No documentation available

Source Code

private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) { // GEN-FIRST:event_jList1ValueChanged
// We need to disable the OK button if no engine type is selected.
if (-1 == jList1.getSelectedIndex()) {
okjButton.setEnabled(false);
} else {
okjButton.setEnabled(true);
}
} // GEN-LAST:event_jList1ValueChanged

Called Methods

No outgoing method calls

hasDifferentAncestor

Class: jfreerails.client.common.RepaintManagerForActiveRendering

Documentation

No documentation available

Source Code

private boolean hasDifferentAncestor(JComponent aComponent) {
Container topLevelAncestor = aComponent.getTopLevelAncestor();
if (null == topLevelAncestor
|| activelyRenderedComponents.contains(topLevelAncestor)) {
return false;
}
return true;
}

Called Methods

No outgoing method calls

IntArray

Class: jfreerails.util.IntArray

Documentation

/**
* Copy (clone) constructor.
*
* @param base
* instance being copied
*/

Source Code

/**
* Copy (clone) constructor.
*
* @param base
* instance being copied
*/
public IntArray(IntArray base) {
super(base);
}

PreMoveException

Class: jfreerails.move.PreMoveException

Documentation

No documentation available

Source Code

public PreMoveException(String s) {
super(s);
}

Called Methods

No outgoing method calls

addD2

Class: jfreerails.util.List2DImpl

Documentation

No documentation available

Source Code

public int addD2(int d1, T element) {
ArrayList<T> d2 = elementData.get(d1);
int index = d2.size();
d2.add(element);
return index;
}

Called Methods

No outgoing method calls

BuildTrackController

Class: jfreerails.client.renderer.BuildTrackController

Documentation

/**
* BuildTrackRenderer
*
* @param readOnlyWorld
* ReadOnlyWorld
*/

Source Code

/**
* BuildTrackRenderer
*
* @param readOnlyWorld
* ReadOnlyWorld
*/
public BuildTrackController(ReadOnlyWorld readOnlyWorld, ModelRoot modelRoot) {
worldDiffs = new WorldDiffs(readOnlyWorld);
realWorld = readOnlyWorld;
path4newTrackFinder = new TrackPathFinder(readOnlyWorld, modelRoot
.getPrincipal());
pathOnExistingTrackFinder = new PathOnTrackFinder(readOnlyWorld);
this.modelRoot = modelRoot;
principal = modelRoot.getPrincipal();
setWorldDiffs(worldDiffs);
}

initPositionStep2

Class: jfreerails.controller.AddTrainPreMove

Documentation

No documentation available

Source Code

TrainMotion initPositionStep2(PathOnTiles path) {
// TODO fix code.
TrainMotion tm = new TrainMotion(path, path.steps(), calTrainLength(),
ConstAcc.STOPPED);
return tm;
}

hasNext

Class: jfreerails.world.common.FreerailsPathIteratorImpl

Documentation

No documentation available

Source Code

public boolean hasNext() {
if (forwards) {
return (position + 1) < points.size();
}
return (position - 1) >= 0;
}

Called Methods

No outgoing method calls

size

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public int size(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
return activityLists.sizeD2(playerIndex);
}

getEngineImages

Class: jfreerails.client.renderer.MyRenderersRoot

Documentation

No documentation available

Source Code

@Override
public TrainImages getEngineImages(int type) {
return this.trainImages;
}

Called Methods

No outgoing method calls

getPrice

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

public Money getPrice() {
return this.properties.getPrice();
}

generateTerrainTypesList

Class: jfreerails.world.top.MapFixtureFactory

Documentation

/** Adds hard coded terrain types. */

Source Code

/** Adds hard coded terrain types. */
private static void generateTerrainTypesList(World world) {
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Country, "Grassland"));
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Urban, "City"));
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Resource, "Mine"));
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Industry, "Factory"));
world.add(SKEY.TERRAIN_TYPES, new TileTypeImpl(
TerrainType.Category.Ocean, "Ocean"));
}

showNetworthGraph

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showNetworthGraph() {
final NetWorthGraphJPanel worthGraph = new NetWorthGraphJPanel();
worthGraph.setup(modelRoot, vl, closeCurrentDialogue);
showContent(worthGraph);
}

savegame

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public void savegame(String saveGameName) {
logger.info("save game as " + saveGameName);
try {
savedGamesManager.saveGame(serverGameModel, saveGameName);
String[] saves = savedGamesManager.getSaveGameNames();
Message2Client request = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.SAVED_GAMES, new ImStringList(
saves));
send2All(request);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

equals

Class: jfreerails.world.player.WorldPrincipal

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (!(o instanceof WorldPrincipal)) {
return false;
}
return (principalName.equals(((WorldPrincipal) o).principalName));
}

Called Methods

No outgoing method calls

getPrice

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

public Money getPrice() {
return new Money(0);
}

Called Methods

No outgoing method calls

removeLastD2

Class: jfreerails.util.List2DImpl

Documentation

No documentation available

Source Code

public T removeLastD2(int d1) {
int last = elementData.get(d1).size() -1;
T element = elementData.get(d1).get(last);
elementData.get(d1).remove(last);
return element;
}

Called Methods

No outgoing method calls

CargoAndTerrainHandlerImpl

Class: jfreerails.server.parser.CargoAndTerrainHandlerImpl

Documentation

No documentation available

Source Code

public CargoAndTerrainHandlerImpl(World w) {
world = w;
}

Called Methods

No outgoing method calls

update

Class: jfreerails.network.specifics.SimpleServerGameModel

Documentation

No documentation available

Source Code

public void update() {
}

Called Methods

No outgoing method calls

nextJButtonActionPerformed

Class: jfreerails.client.view.TrainDialogueJPanel

Documentation

No documentation available

Source Code

private void nextJButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_nextJButtonActionPerformed
// Add your handling code here:
if (wi.next()) {
display(wi.getIndex());
} else {
logger.warning("Couldn't get next");
}
}// GEN-LAST:event_nextJButtonActionPerformed

getDiff

Class: jfreerails.world.top.WorldDiffs

Documentation

No documentation available

Source Code

public Object getDiff(ListKey key){
return listDiff.get(key);
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

@Override
public String toString() {
String s = "PositionOnTrack: " + x + ", " + y + " facing "
+ cameFrom.getOpposite().toString();
return s;
}

set

Class: jfreerails.world.top.World

Documentation

/**
* Replaces the element at the specified position in the specified list with
* the specified element.
*/

Source Code

/**
* Replaces the element at the specified position in the specified list with
* the specified element.
*/
void set(FreerailsPrincipal principal, KEY key, int index,
FreerailsSerializable element);

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.track.TrackRuleProperties

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof TrackRuleProperties) {
TrackRuleProperties test = (TrackRuleProperties) o;
if (rGBvalue == test.getRGBvalue()
&& enableDoubleTrack == test.isEnableDoubleTrack()
&& typeName.equals(test.getTypeName())
&& category == test.category
&& stationRadius == test.stationRadius) {
return true;
}
return false;
}
return false;
}

setWorld

Class: jfreerails.network.specifics.SimpleServerGameModel

Documentation

No documentation available

Source Code

public void setWorld(World w, String[] passwords) {
this.w = w;
this.passwords = passwords.clone();
}

Called Methods

  • _Dummy_.__Array__.clone (external)

MutableCargoBundle

Class: jfreerails.world.cargo.MutableCargoBundle

Documentation

No documentation available

Source Code

public MutableCargoBundle() {
sortedMap = new TreeMap<CargoBatch, Integer>();
}

Called Methods

No outgoing method calls

getKey

Class: jfreerails.world.top.SKEY

Documentation

No documentation available

Source Code

static SKEY getKey(int keyNum) {
return keys[keyNum];
}

Called Methods

No outgoing method calls

skippedEntity

Class: jfreerails.server.parser.CargoAndTerrainParser

Documentation

/**
* This SAX interface method is implemented by the parser.
*
*/

Source Code

/**
* This SAX interface method is implemented by the parser.
*
*/
public final void skippedEntity(java.lang.String name) throws SAXException {
}

Called Methods

No outgoing method calls

getUnderlying

Class: jfreerails.world.top.WorldDiffs

Documentation

No documentation available

Source Code

public ReadOnlyWorld getUnderlying() {
return underlying;
}

Called Methods

No outgoing method calls

createInstance

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public static TrainPositionOnMap createInstance(int[] xpoints, int[] ypoints) {
return new TrainPositionOnMap(xpoints, ypoints, 0d, 0d,
SpeedTimeAndStatus.TrainActivity.READY);
}

Called Methods

No outgoing method calls

getActivities

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

No documentation available

Source Code

ActivityIterator getActivities(FreerailsPrincipal p, int index);

Called Methods

No outgoing method calls

readFromClient

Class: jfreerails.network.Connection2Client

Documentation

/**
* Returns an array containing all the objects read from the client since
* the last time this method or waitForObjectFromClient() was called, if no
* objects have been received, it returns an empty array rather than
* blocking.
*/

Source Code

/**
* Returns an array containing all the objects read from the client since
* the last time this method or waitForObjectFromClient() was called, if no
* objects have been received, it returns an empty array rather than
* blocking.
*/
FreerailsSerializable[] readFromClient() throws IOException;

Called Methods

No outgoing method calls

removeLast

Class: jfreerails.util.ListXDDiffs

Documentation

No documentation available

Source Code

@SuppressWarnings("unchecked")
public T removeLast(int... dim) {
T toRemove;
int last = size(dim) - 1;
int[] array = add2Array(dim, last);
ListKey elementKey = new ListKey(ListKey.Type.Element, listID, array);
if (diffs.containsKey(elementKey)) {
toRemove = (T) diffs.remove(elementKey);
} else {
toRemove = uGet(array);
}
setSize(last, dim);
return toRemove;
}

mouseReleased

Class: jfreerails.client.top.CursorMouseAdapter

Documentation

No documentation available

Source Code

@Override
public void mouseReleased(MouseEvent evt
) {
if (SwingUtilities.isLeftMouseButton(evt)) {
ignoreDragging = false;
setIgnoreKeyEvents(false);
// build a railroad from x,y to current cursor position
if (pressedInside && buildTrack.isBuilding()
&& buildTrack.isBuildTrackSuccessful()) {
// Fix for bug [ 997088 ]
// Is current posisition different from original position?
int x = evt.getX();
int y = evt.getY();
float scale = mapView.getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
int tileX = x / tileSize.width;
int tileY = y / tileSize.height;
if (getCursorPosition().x != tileX
|| getCursorPosition().y != tileY) {
// copy WorldDifferences from buildTrack to World
ImPoint newPosition = buildTrack
.updateWorld(trackBuilder);
setCursorPosition(newPosition);
}
}
pressedInside = false;
buildTrack.hide();
}
}

previousStationActionPerformed

Class: jfreerails.client.view.StationInfoJPanel

Documentation

No documentation available

Source Code

private void previousStationActionPerformed(java.awt.event.ActionEvent evt) {
// GEN-FIRST:event_previousStationActionPerformed
// Add your handling code here:
if (wi.previous()) {
ImPoint p = new ImPoint(((StationModel) wi.getElement())
.getStationX(), ((StationModel) wi.getElement())
.getStationY());
this.modelRoot.setProperty(ModelRoot.Property.CURSOR_POSITION, p);
display();
} else {
throw new IllegalStateException();
}
} // GEN-LAST:event_previousStationActionPerformed

display

Class: jfreerails.client.view.StationInfoJPanel

Documentation

No documentation available

Source Code

private void display() {
if (wi.getRowID() > 0) {
this.previousStation.setEnabled(true);
} else {
this.previousStation.setEnabled(false);
}
if (wi.getRowID() < (wi.size() - 1)) {
this.nextStation.setEnabled(true);
} else {
this.nextStation.setEnabled(false);
}
int stationNumber = wi.getIndex();
String label;
if (stationNumber != WorldIterator.BEFORE_FIRST) {
StationModel station = (StationModel) w.get(modelRoot.getPrincipal(),
KEY.STATIONS, stationNumber);
FreerailsTile tile = (FreerailsTile) w
.getTile(station.x, station.y);
String stationTypeName = tile.getTrackPiece().getTrackRule().getTypeName();
cargoBundleIndex = station.getCargoBundleID();
ImmutableCargoBundle cargoWaiting = (ImmutableCargoBundle) w.get(
modelRoot
.getPrincipal(), KEY.CARGO_BUNDLES, station.getCargoBundleID());
String title = "<h2 align=\"center\">" + station.getStationName()
+ " (" + stationTypeName + ")</h2>";
String table = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"3\"><tr><td>&nbsp;</td>\n <td>Will pay for</td>\n <td>Supplies / cars per year</td><td>Waiting for pickup / car loads</td> </tr>";
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
// get the values
CargoType cargoType = (CargoType) w.get(SKEY.CARGO_TYPES, i);
String demanded = (station.getDemand().isCargoDemanded(i) ? "Yes"
: "No");
int amountSupplied = station.getSupply().getSupply(i);
String supply = (amountSupplied > 0) ? String
.valueOf(amountSupplied
/ WagonType.UNITS_OF_CARGO_PER_WAGON)
: "&nbsp;";
int amountWaiting = cargoWaiting.getAmount(i);
String waiting = (amountWaiting > 0) ? String
.valueOf(amountWaiting
/ WagonType.UNITS_OF_CARGO_PER_WAGON)
: "&nbsp;";
// build the html
table += "<tr>";
table += "<td>" + cargoType.getDisplayName() + "</td>";
table += "<td>" + demanded + "</td>";
table += "<td>" + supply + "</td>";
table += "<td>" + waiting + "</td>";
table += "</tr>";
}
table += "</table>";
label = "<html>" + title + table + "</html>";
} else {
cargoBundleIndex = WorldIterator.BEFORE_FIRST;
label = "<html><h2 align=\"center\">No Station "
+ "Selected</h2></html>";
}
jLabel1.setText(label);
this.repaint();
}

resetPreferredSize

Class: jfreerails.client.view.TrainListCellRenderer

Documentation

No documentation available

Source Code

private void resetPreferredSize() {
int width = 0;
for (int i = 0; i < images.length; i++) {
width += images[i].getWidth(null);
}
this.trainWidth = width;
this.setPreferredSize(new Dimension(width, height));
}

Called Methods

No outgoing method calls

getFinalPosition

Class: jfreerails.world.train.PathOnTiles

Documentation

No documentation available

Source Code

public PositionOnTrack getFinalPosition() {
int x = start.x;
int y = start.y;
for (int i = 0; i < vectors.size(); i++) {
Step v = vectors.get(i);
x += v.deltaX;
y += v.deltaY;
}
int i = vectors.size() - 1;
Step finalStep = vectors.get(i);
PositionOnTrack p = PositionOnTrack.createFacing(x, y, finalStep);
return p;
}

mouseClicked

Class: jfreerails.client.top.CursorMouseAdapter

Documentation

No documentation available

Source Code

@Override
public void mouseClicked(MouseEvent evt) {
boolean isDoubleClick = evt.getClickCount() == 2;
ReadOnlyWorld w = modelRoot.getWorld();
FreerailsPrincipal principal = modelRoot.getPrincipal();
if (SwingUtilities.isLeftMouseButton(evt)) {
int x = evt.getX();
int y = evt.getY();
Double time = (Double) modelRoot.getProperty(Property.TIME);
int clickedTrain = -1;
//Iterate in reverse order since later trains are rendered over earlier ones.
for (int i = w.size(principal, KEY.TRAINS) -1; i >= 0 ; i--) {
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS, i);
TrainAccessor ta = new TrainAccessor(w, principal, i);
TrainPositionOnMap pos = ta.findPosition(time);
List<Map.Entry<Point, Step>> positions = trainRenderer.calcPositions(train, pos);
boolean hit = trainRenderer.isHit(evt.getPoint(), train, positions);
if(hit){
clickedTrain = i;
break;
}
}
if (clickedTrain != -1) {
modelRoot.setProperty(Property.SELECTED_TRAIN, clickedTrain);
if (isDoubleClick) {
dialogueBoxController.showTrainOrders(clickedTrain);
}
} else {
if (isDoubleClick) {
ImPoint cursorPosition = (ImPoint) modelRoot.getProperty(Property.CURSOR_POSITION);
dialogueBoxController.showStationOrTerrainInfo(cursorPosition.x,
cursorPosition.y);
}
}
}
}

toAbrvString

Class: jfreerails.world.common.Step

Documentation

No documentation available

Source Code

public String toAbrvString() {
String name;
switch (deltaY) {
case 1:
name = "s";
break;
case -1:
name = "n";
break;
default:
name = "";
break;
}
switch (deltaX) {
case 1:
name += "e";
break;
case -1:
name += "w";
break;
default:
break;
}
return name;
}

Called Methods

No outgoing method calls

loadFromMap

Class: jfreerails.server.CityEconomicModel

Documentation

No documentation available

Source Code

void loadFromMap(ReadOnlyWorld w, int cityID) {
/* Reset lists of tiles. */
urbanTiles.clear();
industryTiles.clear();
clearTiles.clear();
resourceTiles.clear();
/* Set up the list of industries not at the city. */
industriesNotAtCity.clear();
for (int i = 0; i < w.size(SKEY.TERRAIN_TYPES); i++) {
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
if (type.getCategory().equals(TerrainType.Category.Industry)) {
industriesNotAtCity.add(type);
}
}
stations = 0;
/* Identify city's bounds. */
Rectangle mapRect = new Rectangle(0, 0, w.getMapWidth(), w
.getMapHeight());
CityModel city = (CityModel) w.get(SKEY.CITIES, cityID);
Rectangle cityArea = new Rectangle(city.getCityX() - 3,
city.getCityY() - 3, 7, 7);
cityArea = cityArea.intersection(mapRect);
/* Count tile types. */
for (int x = cityArea.x; x < cityArea.x + cityArea.width; x++) {
for (int y = cityArea.y; y < cityArea.y + cityArea.height; y++) {
FreerailsTile tile = (FreerailsTile) w.getTile(x, y);
/* Count the number of stations at the city. */
if (tile.getTrackPiece().getTrackRule().isStation()) {
stations++;
}
int terrainTypeNumber = tile.getTerrainTypeID();
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES,
terrainTypeNumber);
if (type.getCategory().equals(TerrainType.Category.Urban)) {
urbanTiles.add(new Tile(new Point(x, y), type));
} else if (type.getCategory().equals(
TerrainType.Category.Industry)) {
industryTiles.add(new Tile(new Point(x, y), type));
industriesNotAtCity.remove(type);
} else if (type.getCategory().equals(
TerrainType.Category.Country)) {
clearTiles.add(new Point(x, y));
} else if (type.getCategory().equals(
TerrainType.Category.Resource)) {
resourceTiles.add(new Tile(new Point(x, y), type));
}
}
}
}

TileTypeImpl

Class: jfreerails.world.terrain.TileTypeImpl

Documentation

No documentation available

Source Code

public TileTypeImpl(int rgb, TerrainType.Category terrainCategory,
String terrainType, int rightOfWay, Production[] production,
Consumption[] consumption, Conversion[] conversion,
int tileBuildCost) {
this.terrainType = terrainType;
this.terrainCategory = terrainCategory;
this.rgb = rgb;
this.rightOfWay = rightOfWay;
this.production = new ImList<Production>(production);
this.consumption = new ImList<Consumption>(consumption);
this.conversion = new ImList<Conversion>(conversion);
if (tileBuildCost > 0) {
this.tileBuildCost = new Money(tileBuildCost);
} else {
this.tileBuildCost = null;
}
}

Called Methods

No outgoing method calls

write2map

Class: jfreerails.server.CityEconomicModel

Documentation

No documentation available

Source Code

void write2map(World w) {
for (int i = 0; i < urbanTiles.size(); i++) {
writeTile(w, urbanTiles.get(i));
}
for (int i = 0; i < industryTiles.size(); i++) {
writeTile(w, industryTiles.get(i));
}
for (int i = 0; i < resourceTiles.size(); i++) {
writeTile(w, resourceTiles.get(i));
}
}

getLegalRoutes

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

public Step[] getLegalRoutes(
jfreerails.world.common.Step directionComingFrom) {
return new Step[0];
}

Called Methods

No outgoing method calls

get

Class: jfreerails.world.common.ImList

Documentation

No documentation available

Source Code

public E get(int i) {
return elementData[i];
}

Called Methods

No outgoing method calls

nextSegment

Class: jfreerails.controller.RandomPathFinder

Documentation

No documentation available

Source Code

public void nextSegment(IntLine line) {
p1.setValuesFromInt(trackExplorer.getPosition());
line.x1 = p1.getX() * tileSize + tileSize / 2;
line.y1 = p1.getY() * tileSize + tileSize / 2;
trackExplorer.nextEdge();
trackExplorer.moveForward();
p2.setValuesFromInt(trackExplorer.getPosition());
line.x2 = p2.getX() * tileSize + tileSize / 2;
line.y2 = p2.getY() * tileSize + tileSize / 2;
}

getSoundManager

Class: jfreerails.client.common.SoundManager

Documentation

No documentation available

Source Code

public static SoundManager getSoundManager() {
return soundManager;
}

Called Methods

No outgoing method calls

tryDoMove

Class: jfreerails.move.AddActiveEntityMove

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (index != w.size(principal))
return MoveStatus.moveFailed("index != w.size(listKey, p)");
return MoveStatus.MOVE_OK;
}

NameAndPassword

Class: jfreerails.network.specifics.NameAndPassword

Documentation

No documentation available

Source Code

public NameAndPassword(String u, String p) {
username = u;
password = p;
}

Called Methods

No outgoing method calls

repayBond

Class: jfreerails.world.accounts.BondTransaction

Documentation

No documentation available

Source Code

public static BondTransaction repayBond(int interestRate) {
return new BondTransaction(Category.BOND, interestRate, -1,
BOND_VALUE_REPAY);
}

Called Methods

No outgoing method calls

testSizeD1

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List2DDiff.sizeD1()'
*/
public void testSizeD1() {
assertEquals(0, diffs.sizeD1());
underlying.addD1();
assertEquals(1, diffs.sizeD1());
}

getMapWidth

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

/**
* Returns the width of the map in tiles.
*/

Source Code

/**
* Returns the width of the map in tiles.
*/
int getMapWidth();

Called Methods

No outgoing method calls

removeStationJMenuItemActionPerformed

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void removeStationJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_removeStationJMenuItemActionPerformed
MutableSchedule s = getSchedule();
if(s.getNumOrders() ==0){
logger.warning("Can't remove orders since non exist!");
return;
}
int i = orders.getSelectedIndex();
if(s.getNumOrders() <= i){
logger.warning("Order #"+String.valueOf(i)+" does not exist!");
return;
}
s.removeOrder(i);
sendUpdateMove(s);
}// GEN-LAST:event_removeStationJMenuItemActionPerformed

equals

Class: jfreerails.world.track.TrackSection

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final TrackSection other = (TrackSection) obj;
if (step == null) {
if (other.step != null)
return false;
} else if (!step.equals(other.step))
return false;
if (tile == null) {
if (other.tile != null)
return false;
} else if (!tile.equals(other.tile))
return false;
return true;
}

tailsAreEqual

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public static boolean tailsAreEqual(TrainPositionOnMap a,
TrainPositionOnMap b) {
int aTailX = a.getX(a.getLength() - 1);
int aTailY = a.getY(a.getLength() - 1);
int bTailX = b.getX(b.getLength() - 1);
int bTailY = b.getY(b.getLength() - 1);
if (aTailX == bTailX && aTailY == bTailY) {
return true;
}
return false;
}

addD1

Class: jfreerails.util.List2DImpl

Documentation

No documentation available

Source Code

public int addD1() {
elementData.add(new ArrayList<T>());
return elementData.size() -1;
}

Called Methods

No outgoing method calls

initServer

Class: jfreerails.launcher.Launcher

Documentation

No documentation available

Source Code

private void initServer() {
SavedGamesManager gamesManager = new SavedGamesManagerImpl();
server = new FreerailsGameServer(gamesManager);
ServerGameModelImpl serverGameModel = new ServerGameModelImpl();
server.setServerGameModel(serverGameModel);
/*
* Set the server field on the connected players panel so that it can
* keep track of who is connected.
*/
ConnectedPlayersJPanel cp = (ConnectedPlayersJPanel) wizardPages[3];
cp.server = server;
server.addPropertyChangeListener(cp);
cp.updateListOfPlayers();
}

testThatStockIsIssued

Class: jfreerails.server.MapFixtureFactory2Test

Documentation

No documentation available

Source Code

public void testThatStockIsIssued(){
FreerailsPrincipal p = w1.getPlayer(0).getPrincipal();
int stock = 0;
Money cash = w1.getCurrentBalance(p);
assertEquals(new Money(1000000), cash);
int numberOfTransactions = w1.getNumberOfTransactions(p);
assertTrue(numberOfTransactions > 0);
for(int i = 0; i < numberOfTransactions; i++){
Transaction t = w1.getTransaction(p, i);
if(t.getCategory().equals(Transaction.Category.ISSUE_STOCK)){
AddItemTransaction ait = (AddItemTransaction)t;
stock += ait.getQuantity();
}
}
assertEquals(100000, stock);
}

testAddAndRemove

Class: jfreerails.util.List1DDiffsTest

Documentation

No documentation available

Source Code

public void testAddAndRemove(){
list.add(String.valueOf(1));
assertEquals( String.valueOf(1), diffs.get(0));
int i = diffs.add(String.valueOf(2));
assertEquals(1, i);
assertEquals( String.valueOf(1), diffs.get(0));
assertEquals(diffs.get(1), String.valueOf(2));
assertEquals(2, diffs.size());
assertEquals(2, map.size());
Object removed = diffs.removeLast();
assertEquals(String.valueOf(2), removed);
assertEquals(1, diffs.size());
assertEquals(0, map.size());
removed = diffs.removeLast();
assertEquals(String.valueOf(1), removed);
assertEquals(0, diffs.size());
assertEquals(1, map.size());
}

start_TrackPieceTemplate

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void start_TrackPieceTemplate(final Attributes meta)
throws SAXException {
legalTemplates.add(meta.getValue("trackTemplate"));
}

Called Methods

No outgoing method calls

addIncome

Class: jfreerails.controller.StockPriceCalculatorTest

Documentation

No documentation available

Source Code

private void addIncome(long income) {
CargoBatch batch = new CargoBatch(0, 0, 0, 0, 0);
Transaction t = new DeliverCargoReceipt(new Money(income), 10, 0,
batch, 0);
FreerailsPrincipal princ = w.getPlayer(0).getPrincipal();
w.addTransaction(princ, t);
}

mouseDragged

Class: jfreerails.client.view.MapViewJComponentMouseAdapter

Documentation

No documentation available

Source Code

@Override
public void mouseDragged(MouseEvent evt) {
if (SwingUtilities.isRightMouseButton(evt)) {
sigmadelta.x += evt.getX() - lastMouseLocation.x;
sigmadelta.y += evt.getY() - lastMouseLocation.y;
int tileSize = (int) getScale();
tiledelta.x = (sigmadelta.x * GRANULARITY) / tileSize;
tiledelta.y = (sigmadelta.y * GRANULARITY) / tileSize;
tiledelta.x = ((tiledelta.x * tileSize) / GRANULARITY)
* LINEAR_ACCEL;
tiledelta.y = ((tiledelta.y * tileSize) / GRANULARITY)
* LINEAR_ACCEL;
Rectangle vr = MapViewJComponentConcrete.this.getVisibleRect();
Rectangle bounds = MapViewJComponentConcrete.this.getBounds();
int temp; // respect bounds
if ((temp = vr.x - tiledelta.x) < 0) {
sigmadelta.x += temp / LINEAR_ACCEL;
tiledelta.x += temp;
} else if ((temp = (bounds.width) - (vr.x + vr.width)
+ tiledelta.x) < 0) {
sigmadelta.x -= temp / LINEAR_ACCEL;
tiledelta.x -= temp;
}
if ((temp = vr.y - tiledelta.y) < 0) {
sigmadelta.y += temp / LINEAR_ACCEL;
tiledelta.y += temp;
} else if ((temp = (bounds.height) - (vr.y + vr.height)
+ tiledelta.y) < 0) {
sigmadelta.y -= temp / LINEAR_ACCEL;
tiledelta.y -= temp;
}
if (tiledelta.x != 0 || tiledelta.y != 0) {
vr.x -= tiledelta.x;
vr.y -= tiledelta.y;
MapViewJComponentConcrete.this.scrollRectToVisible(vr);
sigmadelta.x -= tiledelta.x / LINEAR_ACCEL;
sigmadelta.y -= tiledelta.y / LINEAR_ACCEL;
lastMouseLocation.x -= tiledelta.x;
lastMouseLocation.y -= tiledelta.y;
}
MapViewJComponentConcrete.robot.mouseMove(screenLocation.x,
screenLocation.y);
}
}

ActivityIteratorImpl

Class: jfreerails.world.top.ActivityIteratorImpl

Documentation

No documentation available

Source Code

public ActivityIteratorImpl(int playerIndex, int index) {
currentList = activityLists.get(playerIndex, index);
size = currentList.size();
ant = currentList.get(activityIndex);
}

setPosition

Class: jfreerails.client.renderer.StationRadiusRenderer

Documentation

No documentation available

Source Code

public void setPosition(int x, int y) {
this.x = x;
this.y = y;
}

Called Methods

No outgoing method calls

getServerDetails

Class: jfreerails.network.LocalConnection

Documentation

No documentation available

Source Code

public String getServerDetails() {
return SERVER_IN_SAME_JVM;
}

Called Methods

No outgoing method calls

getTarget

Class: jfreerails.controller.TrainAccessor

Documentation

/**
* @return the location of the station the train is currently heading
* towards.
*/

Source Code

/**
* @return the location of the station the train is currently heading
* towards.
*/
public ImPoint getTarget() {
TrainModel train = (TrainModel) w.get(p, KEY.TRAINS, id);
int scheduleID = train.getScheduleID();
ImmutableSchedule schedule = (ImmutableSchedule) w.get(
p, KEY.TRAIN_SCHEDULES, scheduleID);
int stationNumber = schedule.getStationToGoto();
if (-1 == stationNumber) {
// There are no stations on the schedule.
return new ImPoint(0, 0);
}
StationModel station = (StationModel) w.get(p,
KEY.STATIONS, stationNumber);
return new ImPoint(station.x, station.y);
}

ToAndFroPathIteratorTest

Class: jfreerails.controller.ToAndFroPathIteratorTest

Documentation

No documentation available

Source Code

public ToAndFroPathIteratorTest(String arg0) {
super(arg0);
}

Called Methods

No outgoing method calls

setUp

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
setHasSetupBeenCalled(true);
setupWorld();
}

calculatePrice

Class: jfreerails.controller.SharePriceCalculator

Documentation

No documentation available

Source Code

public long calculatePrice() {
assert totalShares > 0;
assert totalShares >= treasuryStock + otherRRStakes;
assert stockholderEquity > 0;
long price;
long currentValue = networth + stockholderEquity;
long expectedIncrease = profitsLastYear * 5;
int publicOwnedShares = totalShares - treasuryStock - otherRRStakes;
price = 2 * (currentValue + expectedIncrease)
/ (2 * publicOwnedShares + otherRRStakes);
return price;
}

Called Methods

No outgoing method calls

getNewMapName

Class: jfreerails.launcher.SelectMapJPanel

Documentation

No documentation available

Source Code

public String getNewMapName() {
return (String) newmapsJList.getSelectedValue();
}

Called Methods

No outgoing method calls

processMove

Class: jfreerails.network.specifics.MoveChainFork

Documentation

No documentation available

Source Code

public void processMove(Move move) {
for (int i = 0; i < moveReceivers.size(); i++) {
MoveReceiver m = moveReceivers.get(i);
m.processMove(move);
}
splitMove(move);
}

itemAdded

Class: jfreerails.network.specifics.SimpleServerGameModel

Documentation

No documentation available

Source Code

public void itemAdded(KEY key, int index, FreerailsPrincipal principal) {
}

Called Methods

No outgoing method calls

thisRRHasStakeIn

Class: jfreerails.controller.FinancialDataGatherer

Documentation

No documentation available

Source Code

public boolean thisRRHasStakeIn(int otherReId){
return stockInRRs[otherReId] > 0;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.terrain.Conversion

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Conversion))
return false;
final Conversion conversion = (Conversion) o;
if (input != conversion.input)
return false;
if (output != conversion.output)
return false;
return true;
}

Called Methods

No outgoing method calls

getInitialPosition

Class: jfreerails.world.train.TrainMotion

Documentation

No documentation available

Source Code

public double getInitialPosition() {
return initialPosition;
}

Called Methods

No outgoing method calls

updateListOfPlayers

Class: jfreerails.launcher.ConnectedPlayersJPanel

Documentation

No documentation available

Source Code

void updateListOfPlayers() {
if (null != server) {
String[] playerNames = server.getPlayerNames();
playerNames = playerNames.length == 0 ? new String[] { "No players are logged on!" }
: playerNames;
setListOfPlayers(playerNames);
}
}

equals

Class: jfreerails.network.specifics.NameAndPassword

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object obj) {
if (!(obj instanceof NameAndPassword))
return false;
NameAndPassword test = (NameAndPassword) obj;
return test.password.equals(password) && test.username.equals(username);
}

Called Methods

No outgoing method calls

getCurrentBalance

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public Money getCurrentBalance(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
return currentBalance.get(playerIndex);
}

paintComponent

Class: jfreerails.client.view.TrainListCellRenderer

Documentation

No documentation available

Source Code

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 0;
if (this.centerTrain) {
x = (this.getWidth() - this.trainWidth) / 2;
}
for (int i = 0; i < images.length; i++) {
g.drawImage(images[i], x, 0, null);
x += images[i].getWidth(null);
}
}

Called Methods

No outgoing method calls

size

Class: jfreerails.util.List1DDiff

Documentation

No documentation available

Source Code

public int size() {
return super.size(new int[0]);
}

getTrackRule

Class: jfreerails.world.track.NullTrackPiece

Documentation

No documentation available

Source Code

public TrackRule getTrackRule() {
return NullTrackType.getInstance();
}

execute

Class: jfreerails.controller.Message2Client

Documentation

/** Executes this command on the specified ClientControlInterface. */

Source Code

/** Executes this command on the specified ClientControlInterface. */
MessageStatus execute(ClientControlInterface client);

Called Methods

No outgoing method calls

generateMove

Class: jfreerails.move.UpgradeTrackMove

Documentation

No documentation available

Source Code

public static UpgradeTrackMove generateMove(TrackPiece before,
TrackPiece after, ImPoint p) {
ChangeTrackPieceMove m = new ChangeTrackPieceMove(before, after, p);
return new UpgradeTrackMove(m);
}

Called Methods

No outgoing method calls

testRemoveLastD1

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List2DDiff.removeLastD1()'
*/
public void testRemoveLastD1() {
underlying.addD1();
underlying.addD1();
assertEquals(2, diffs.sizeD1());
int i = diffs.removeLastD1();
assertEquals(1, i);
assertEquals(1, diffs.sizeD1());
}

display

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

public void display(int newTrainNumber) {
this.trainNumber = newTrainNumber;
FreerailsPrincipal principal = modelRoot.getPrincipal();
ReadOnlyWorld w = modelRoot.getWorld();
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
newTrainNumber);
this.scheduleID = train.getScheduleID();
listModel = new TrainOrdersListModel(w, newTrainNumber, principal);
orders.setModel(listModel);
orders.setFixedCellWidth(250);
listModel.fireRefresh();
enableButtons();
}

start_Types

Class: jfreerails.server.parser.CargoAndTerrainHandler

Documentation

/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/

Source Code

/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/
public void start_Types(final Attributes meta) throws SAXException;

Called Methods

No outgoing method calls

prevButtonActionPerformed

Class: jfreerails.launcher.Launcher

Documentation

No documentation available

Source Code

private void prevButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_prevButtonActionPerformed
CardLayout cl = (CardLayout) jPanel1.getLayout();
nextIsStart = false;
hideAllMessages();
switch (currentPage) {
case 1:
cl.previous(jPanel1);
currentPage--;
prevButton.setEnabled(false);
break;
case 2:
LauncherPanel1 panel = (LauncherPanel1) wizardPages[0];
if (panel.getMode() == LauncherPanel1.MODE_JOIN_NETWORK_GAME) {
currentPage = 0;
cl.show(jPanel1, "0");
prevButton.setEnabled(false);
} else {
currentPage--;
cl.previous(jPanel1);
}
}
}// GEN-LAST:event_prevButtonActionPerformed

testGetNearestVector

Class: jfreerails.world.common.StepTest

Documentation

No documentation available

Source Code

public void testGetNearestVector() {
// Each vector should be the nearest to itself!
Step[] vectors = Step.getList();
for (int i = 0; i < vectors.length; i++) {
Step v = vectors[i];
Step v2 = Step.getNearestVector(v.deltaX, v.deltaY);
assertEquals(v, v2);
}
assertNearest(n, 0, -1);
assertNearest(n, 0, -99);
assertNearest(n, 2, -5);
assertNearest(n, -2, -5);
assertNearest(s, 2, 5);
assertNearest(w, -5, -1);
assertNearest(sw, -4, 3);
assertNearest(ne, 10, -6);
assertNearest(ne, 10, -6);
}

TrackPieceRendererImpl

Class: jfreerails.client.renderer.TrackPieceRendererImpl

Documentation

No documentation available

Source Code

public TrackPieceRendererImpl(ReadOnlyWorld w, ImageManager imageManager,
int typeNumber) throws IOException {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, typeNumber);
this.typeName = trackRule.getTypeName();
for (int i = 0; i < 512; i++) {
if (trackRule.testTrackPieceLegality(i)) {
String fileName = generateFilename(i, getTrackTypeName());
trackPieceIcons[i] = imageManager.getImage(fileName);
}
}
}

Tile

Class: jfreerails.server.Tile

Documentation

No documentation available

Source Code

public Tile(final Point p, final TerrainType type) {
this.p = p;
this.type = type;
}

Called Methods

No outgoing method calls

hasNext

Class: jfreerails.world.train.TrainPathIterator

Documentation

No documentation available

Source Code

public boolean hasNext() {
return intIterator.hasNextInt();
}

Player

Class: jfreerails.world.player.Player

Documentation

/**
* Used by the server to generate a player with a particular name and public
* key.
*
*/

Source Code

/**
* Used by the server to generate a player with a particular name and public
* key.
*
*/
public Player(String name, int id) {
this.name = name;
// this.publicKey = publicKey;
// privateData = new PrivateData();
this.principal = new PlayerPrincipal(id, name);
}

Called Methods

No outgoing method calls

getNextClientCommandId

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

private int getNextClientCommandId() {
return commandID++;
}

Called Methods

No outgoing method calls

refreshTile

Class: jfreerails.client.view.MapViewJComponentConcrete

Documentation

No documentation available

Source Code

public void refreshTile(int x, int y) {
throw new UnsupportedOperationException();
}

Called Methods

No outgoing method calls

getNumRepaintRequests

Class: jfreerails.client.common.RepaintManagerForActiveRendering

Documentation

No documentation available

Source Code

public static long getNumRepaintRequests() {
return numRepaintRequests;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.common.ImStringList

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImStringList))
return false;
final ImStringList imStringList = (ImStringList) o;
if (!Arrays.equals(strings, imStringList.strings))
return false;
return true;
}

Called Methods

No outgoing method calls

checkBounds

Class: jfreerails.util.ListXDDiffs

Documentation

No documentation available

Source Code

private int[] checkBounds(int... i) {
int[] dim = removeFromArray(i);
int last = i[i.length - 1];
if (last >= size(dim))
throw new IndexOutOfBoundsException(String.valueOf(last));
return dim;
}

FPScounter

Class: jfreerails.client.top.FPScounter

Documentation

No documentation available

Source Code

FPScounter() {
this.fontSize = 10;
bgColor = new Color(0, 0, 128);
}

Called Methods

No outgoing method calls

dumpImages

Class: jfreerails.client.renderer.TileRenderer

Documentation

/** Adds the images this TileRenderer uses to the specified ImageManager. */

Source Code

/** Adds the images this TileRenderer uses to the specified ImageManager. */
void dumpImages(ImageManager imageManager);

Called Methods

No outgoing method calls

getMaintenanceCost

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

public Money getMaintenanceCost() {
return properties.getMaintenanceCost();
}

nextMotion

Class: jfreerails.controller.MoveTrainPreMove

Documentation

No documentation available

Source Code

TrainMotion nextMotion(ReadOnlyWorld w, Step v) {
TrainMotion motion = lastMotion(w);
SpeedAgainstTime speeds = nextSpeeds(w, v);
PathOnTiles currentTiles = motion.getTiles(motion.duration());
PathOnTiles pathOnTiles = currentTiles.addSteps(v);
return new TrainMotion(pathOnTiles, currentTiles.steps(), motion
.getTrainLength(), speeds);
}

read

Class: jfreerails.util.CompressedInputStream

Documentation

No documentation available

Source Code

@Override
public int read() throws IOException {
if (maxReadIndex - readIndex == 0 && !readNextBuffer()) {
return -1;
}
byte b = buffer[readIndex++];
if (b < 0) {
return 256 + b;
}
return b;
}

getMapSizeInPixels

Class: jfreerails.client.view.DetailMapRenderer

Documentation

No documentation available

Source Code

public Dimension getMapSizeInPixels() {
return mapSizeInPixels;
}

Called Methods

No outgoing method calls

abandonSearch

Class: jfreerails.controller.SimpleAStarPathFinder

Documentation

No documentation available

Source Code

public void abandonSearch() {
path = new IntArray();
searchStartTime = 0;
bestPath = PATH_NOT_FOUND;
bestPathF = Integer.MAX_VALUE;
// initialize the open list
openList.clear();
// initialize the closed list
closedList.clear();
shortestPath.clear();
startingPositions.clear();
status = SEARCH_NOT_STARTED;
}

getEdgeCost

Class: jfreerails.controller.FlatTrackExplorer

Documentation

No documentation available

Source Code

public int getEdgeCost() {
return (int) Math.round(currentBranch.cameFrom().getLength());
}

getNumberOfKeys

Class: jfreerails.world.top.KEY

Documentation

No documentation available

Source Code

static int getNumberOfKeys() {
return numberOfKeys;
}

Called Methods

No outgoing method calls

FinancialDataGatherer

Class: jfreerails.controller.FinancialDataGatherer

Documentation

No documentation available

Source Code

public FinancialDataGatherer(ReadOnlyWorld w, FreerailsPrincipal principal) {
super(w, principal);
stockInRRs = new int [w.getNumberOfPlayers()];
calculateValues();
this.playerID = w.getID(principal);
}

getSourceY

Class: jfreerails.world.cargo.CargoBatch

Documentation

No documentation available

Source Code

public int getSourceY() {
return sourceY;
}

Called Methods

No outgoing method calls

testMove

Class: jfreerails.move.NextActivityMoveTest

Documentation

No documentation available

Source Code

@Override
public void testMove() {
World w = getWorld();
FreerailsPrincipal principal = getPrincipal();
Activity act = new WorldImplTest.TestActivity(50);
w.addActiveEntity(principal, act);
Activity act2 = new WorldImplTest.TestActivity(60);
Move move = new NextActivityMove(act2, 0,
principal);
assertSurvivesSerialisation(move);
assertOkAndRepeatable(move);
}

CargoAndTerrainParser

Class: jfreerails.server.parser.CargoAndTerrainParser

Documentation

/**
* Creates a parser instance.
*
* @param handler
* handler interface implementation (never <code>null</code>
* @param resolver
* SAX entity resolver implementation or <code>null</code>. It
* is recommended that it could be able to resolve at least the
* DTD.
*/

Source Code

/**
* Creates a parser instance.
*
* @param handler
* handler interface implementation (never <code>null</code>
* @param resolver
* SAX entity resolver implementation or <code>null</code>. It
* is recommended that it could be able to resolve at least the
* DTD.
*/
public CargoAndTerrainParser(final CargoAndTerrainHandler handler,
final EntityResolver resolver) {
this.handler = handler;
this.resolver = resolver;
buffer = new StringBuffer(111);
context = new java.util.Stack<Object[]>();
}

Called Methods

No outgoing method calls

sendCommand

Class: jfreerails.network.specifics.FreerailsClient

Documentation

No documentation available

Source Code

public void sendCommand(Message2Server c) {
write(c);
}

AddStationMove

Class: jfreerails.move.AddStationMove

Documentation

No documentation available

Source Code

private AddStationMove(Move[] moves) {
super(moves);
}

pushDownJMenuItemActionPerformed

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void pushDownJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_pushDownJMenuItemActionPerformed
MutableSchedule s = getSchedule();
int i = orders.getSelectedIndex();
s.pushDown(i);
sendUpdateMove(s);
orders.setSelectedIndex(i + 1);
}// GEN-LAST:event_pushDownJMenuItemActionPerformed

put

Class: jfreerails.util.LRUCache

Documentation

/**
* Adds an entry to this cache. If the cache is full, the LRU (least
* recently used) entry is dropped.
*
* @param key
* the key with which the specified value is to be associated.
* @param value
* a value to be associated with the specified key.
*/

Source Code

/**
* Adds an entry to this cache. If the cache is full, the LRU (least
* recently used) entry is dropped.
*
* @param key
* the key with which the specified value is to be associated.
* @param value
* a value to be associated with the specified key.
*/
public synchronized void put(K key, V value) {
map.put(key, value);
}

Called Methods

No outgoing method calls

getElement

Class: jfreerails.world.top.NonNullElements

Documentation

No documentation available

Source Code

public FreerailsSerializable getElement() {
return listGet(index);
}

setVisible

Class: jfreerails.client.view.TrainListJPanel

Documentation

No documentation available

Source Code

@Override
public void setVisible(boolean aFlag) {
if (aFlag && null != world) {
// jList1.setModel(new World2ListModelAdapter(world,
// KEY.TRAINS,principal));
}
super.setVisible(aFlag);
}

Called Methods

No outgoing method calls

removeLastD2

Class: jfreerails.util.List2D

Documentation

No documentation available

Source Code

T removeLastD2(int d1);

Called Methods

No outgoing method calls

moveForward

Class: jfreerails.controller.FlatTrackExplorer

Documentation

No documentation available

Source Code

public void moveForward() {
if (beforeFirst) {
throw new IllegalStateException();
}
this.setPosition(this.getVertexConnectedByEdge());
}

calRevenue

Class: jfreerails.client.view.IncomeStatementGenerator

Documentation

/** Calculates the total revenue from the specified cargo type. */

Source Code

/** Calculates the total revenue from the specified cargo type. */
Money calRevenue(Categories cargoCategory) {
long amount = 0;
for (int i = 0; i < w.getNumberOfTransactions(this.principal); i++) {
Transaction t = w.getTransaction(principal, i);
GameTime time = w.getTransactionTimeStamp(principal, i);
if (t instanceof DeliverCargoReceipt
&& cal.getYear(time.getTicks()) >= this.startyear) {
DeliverCargoReceipt dcr = (DeliverCargoReceipt) t;
int cargoType = dcr.getCb().getCargoType();
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, cargoType);
if (ct.getCategory().equals(cargoCategory)) {
amount += dcr.deltaCash().getAmount();
}
}
}
return new Money(amount);
}

equals

Class: jfreerails.world.train.TrainMotion

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TrainMotion))
return false;
final TrainMotion trainMotion = (TrainMotion) o;
if (trainLength != trainMotion.trainLength)
return false;
if (!path.equals(trainMotion.path))
return false;
if (!speeds.equals(trainMotion.speeds))
return false;
return true;
}

ScreenHandler

Class: jfreerails.controller.ScreenHandler

Documentation

No documentation available

Source Code

public ScreenHandler(JFrame f, int mode, DisplayMode displayMode) {
this.displayMode = displayMode;
frame = f;
this.mode = mode;
}

Called Methods

No outgoing method calls

savegame

Class: jfreerails.controller.ServerControlInterface

Documentation

No documentation available

Source Code

void savegame(String saveGameName);

Called Methods

No outgoing method calls

getBuildCost

Class: jfreerails.world.terrain.TileTypeImpl

Documentation

No documentation available

Source Code

public Money getBuildCost() {
return tileBuildCost;
}

Called Methods

No outgoing method calls

PositionOnTrack

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

public PositionOnTrack() {
}

Called Methods

No outgoing method calls

end_Cargo_Types

Class: jfreerails.server.parser.CargoAndTerrainHandlerImpl

Documentation

No documentation available

Source Code

public void end_Cargo_Types() throws SAXException {
// no need to do anything here.
}

Called Methods

No outgoing method calls

loadGame

Class: jfreerails.network.specifics.SavedGamesManager

Documentation

No documentation available

Source Code

Serializable loadGame(String name) throws IOException;

Called Methods

No outgoing method calls

setPriorityOrders

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public void setPriorityOrders(TrainOrdersModel order) {
if (hasPriorityOrders) {
// Replace existing priority orders.
orders.set(PRIORITY_ORDERS, order);
} else {
// Insert priority orders at position 0;
hasPriorityOrders = true;
orders.add(PRIORITY_ORDERS, order);
nextScheduledOrder++;
}
}

Called Methods

No outgoing method calls

setupVectors

Class: jfreerails.world.common.Step

Documentation

No documentation available

Source Code

private static Step[][] setupVectors() {
int t = 1;
Step[][] tvectors = new Step[3][3];
for (int y = -1; y <= 1; y++) {
for (int x = -1; x <= 1; x++) {
if ((0 != x) || (0 != y)) {
tvectors[x + 1][y + 1] = new Step(x, y, t);
}
t = t << 1;
}
}
return tvectors;
}

Called Methods

No outgoing method calls

SimpleComponentFactoryImpl2

Class: experimental.SimpleComponentFactoryImpl2

Documentation

/** Creates new SimpleComponentFactoryImpl */

Source Code

/** Creates new SimpleComponentFactoryImpl */
public SimpleComponentFactoryImpl2() {
}

Called Methods

No outgoing method calls

tryUndoMove

Class: jfreerails.move.ChangeTileMove

Documentation

No documentation available

Source Code

public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
FreerailsTile actual = (FreerailsTile) w.getTile(x, y);
if (actual.equals(after)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + after + " but found "
+ actual);
}

getLegalConfigurationsIterator

Class: jfreerails.world.track.TrackRule

Documentation

No documentation available

Source Code

Iterator<TrackConfiguration> getLegalConfigurationsIterator();

Called Methods

No outgoing method calls

flush

Class: jfreerails.network.AbstractInetConnection

Documentation

No documentation available

Source Code

public void flush() throws IOException {
inetConnection.flush();
}

ChangeTrackPieceMove

Class: jfreerails.move.ChangeTrackPieceMove

Documentation

No documentation available

Source Code

public ChangeTrackPieceMove(TrackPiece before, TrackPiece after, ImPoint p) {
trackPieceBefore = before;
trackPieceAfter = after;
location = p;
}

Called Methods

No outgoing method calls

getInstance

Class: jfreerails.world.track.NullTrackPiece

Documentation

No documentation available

Source Code

public static TrackPiece getInstance() {
return nullTrackPiece;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.station.PlannedTrain

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return engineType;
}

Called Methods

No outgoing method calls

getTile

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

/**
* Returns the tile at the specified position on the map.
*/

Source Code

/**
* Returns the tile at the specified position on the map.
*/
FreerailsSerializable getTile(int x, int y);

Called Methods

No outgoing method calls

getCargoOnTrain

Class: jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest

Documentation

/**
* Retrieves the cargo bundle that the train is carrying from the world
* object.
*/

Source Code

/**
* Retrieves the cargo bundle that the train is carrying from the world
* object.
*/
private ImmutableCargoBundle getCargoOnTrain() {
TrainModel train = (TrainModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.TRAINS,
0);
ImmutableCargoBundle cargoOnTrain = (ImmutableCargoBundle) w.get(
MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES,
train.getCargoBundleID());
return cargoOnTrain;
}

ArrayBase

Class: jfreerails.util.ArrayBase

Documentation

/**
* Copy (clone) constructor.
*
* @param base
* instance being copied
*/

Source Code

/**
* Copy (clone) constructor.
*
* @param base
* instance being copied
*/
public ArrayBase(ArrayBase base) {
super(base);
System.arraycopy(base.getArray(), 0, getArray(), 0, base.countPresent);
countPresent = base.countPresent;
}

paintTrainCrash

Class: jfreerails.client.renderer.TrainRenderer

Documentation

No documentation available

Source Code

// @SonnyZ
// This code renders the explosion that occurs when 2 trains crash on the
// map
public void paintTrainCrash(Graphics g, TrainPositionOnMap s) {
// check to see if there is a train
// if (s == null) {
// return;
// }
// // Get the image for that frame of the explosion
// Image explosionImage = rr
// .getExplosionImage(s.getFrameCt() - 1);
// // draw the image
// for (int i = 0; i < s.getLength() - 1; i++) {
// Point wagonCenter = new Point(s.getX(i), s.getY(i));
// g.drawImage(explosionImage, wagonCenter.x - 15, wagonCenter.y - 15, null);
//
// }
// // increment the frame count
// s.incrementFramCt();
}

Called Methods

No outgoing method calls

TrainPathIterator

Class: jfreerails.world.train.TrainPathIterator

Documentation

No documentation available

Source Code

public TrainPathIterator(FreerailsIntIterator i) {
intIterator = i;
p2.setValuesFromInt(intIterator.nextInt());
}

formMousePressed

Class: jfreerails.client.common.MyGlassPanel

Documentation

No documentation available

Source Code

// GEN-LAST:event_formMouseMoved
private void formMousePressed(java.awt.event.MouseEvent evt) { // GEN-FIRST:event_formMousePressed
// Add your handling code here:
}

Called Methods

No outgoing method calls

assertMoveDoMoveIsOk

Class: jfreerails.move.ChangeTrackPieceMoveTest

Documentation

No documentation available

Source Code

protected void assertMoveDoMoveIsOk(TrackPiece oldTrackPiece,
TrackPiece newTrackPiece) {
TrackMove move;
MoveStatus moveStatus;
move = new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece,
new ImPoint(0, 0));
moveStatus = move.doMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(moveStatus);
assertEquals(true, moveStatus.isOk());
TrackConfiguration actual = ((FreerailsTile)getWorld().getTile(0, 0)).getTrackPiece().getTrackConfiguration();
assertEquals(newTrackPiece.getTrackConfiguration(),
actual);
}

startGame

Class: jfreerails.launcher.Launcher

Documentation

No documentation available

Source Code

private void startGame() {
CardLayout cl = (CardLayout) jPanel1.getLayout();
cl.show(jPanel1, "4");
setButtonsVisible(false);
LauncherPanel1 lp = (LauncherPanel1) wizardPages[0];
SelectMapJPanel msp = (SelectMapJPanel) wizardPages[1];
ClientOptionsJPanel cop = (ClientOptionsJPanel) wizardPages[2];
ConnectedPlayersJPanel cp = (ConnectedPlayersJPanel) wizardPages[3];
boolean recover = false;
int mode;
switch (lp.getMode()) {
case LauncherPanel1.MODE_SINGLE_PLAYER:
try {
mode = cop.getScreenMode();
client = new GUIClient(cop.getPlayerName(), progressPanel,
mode, cop.getDisplayMode());
if (isNewGame()) {
initServer();
}
client.connect(server, cop.getPlayerName(), "password");
setServerGameModel();
} catch (IOException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} finally {
if (recover) {
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setButtonsVisible(true);
currentPage = 1;
cl.show(jPanel1, "1");
return;
}
}
startThread(server, client);
break;
case LauncherPanel1.MODE_START_NETWORK_GAME:
// LL: I don't think this code ever executes now that there is a
// connected players screen.
try {
setServerGameModel();
currentPage = 3;
String[] playerNames = server.getPlayerNames();
playerNames = playerNames.length == 0 ? new String[] { "No players are connected." }
: playerNames;
cp.setListOfPlayers(playerNames);
cl.show(jPanel1, "3");
setNextEnabled(false);
} catch (IOException e) {
// We end up here if an Exception was thrown when loading a
// saved game.
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} finally {
if (recover) {
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setNextEnabled(true);
currentPage = 1;
setButtonsVisible(true);
cl.show(jPanel1, "1");
return;
}
}
break;
case LauncherPanel1.MODE_JOIN_NETWORK_GAME:
mode = cop.getScreenMode();
try {
InetSocketAddress serverInetAddress = cop
.getRemoteServerAddress();
if (null == serverInetAddress) {
throw new NullPointerException("Couldn't resolve hostname.");
}
String playerName = cop.getPlayerName();
client = new GUIClient(playerName, progressPanel, mode, cop
.getDisplayMode());
String hostname = serverInetAddress.getHostName();
int port = serverInetAddress.getPort();
setInfoText("Connecting to server...", LauncherInterface.INFO);
LogOnResponse logOnResponse = client.connect(hostname, port,
playerName, "password");
if (logOnResponse.isSuccessful()) {
setInfoText("Logged on and waiting for game to start.", LauncherInterface.INFO);
startThread(client);
} else {
recover = true;
setInfoText(logOnResponse.getMessage(),
LauncherInterface.WARNING);
}
} catch (IOException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} catch (NullPointerException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} finally {
if (recover) {
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setButtonsVisible(true);
cl.show(jPanel1, "2");
return;
}
}
break;
case LauncherPanel1.MODE_SERVER_ONLY:
if (msp.validateInput()) {
initServer();
try {
setServerGameModel();
prepare2HostNetworkGame(msp.getServerPort());
setNextEnabled(true);
} catch (NullPointerException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} catch (IOException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
recover = true;
} finally {
if (recover) {
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setButtonsVisible(true);
return;
}
}
}
}// End of switch statement
}

findTargets

Class: jfreerails.controller.TrackPathFinder

Documentation

No documentation available

Source Code

private int[] findTargets(ImPoint targetPoint) {
FreerailsTile tile = (FreerailsTile) world.getTile(targetPoint.x,
targetPoint.y);
TrackPiece trackPiece = tile.getTrackPiece();
int ruleNumber = trackPiece.getTrackTypeID();
int[] targetInts;
if (tile.hasTrack()) {
/*
* If there is already track here, we need to check what directions
* we can build in without creating an illegal track config.
*/
TrackRule trackRule = (TrackRule) world.get(SKEY.TRACK_RULES,
ruleNumber);
/* Count number of possible directions. */
ArrayList<Step> possibleDirections = new ArrayList<Step>();
for (int i = 0; i < 8; i++) {
Step direction = Step.getInstance(i);
TrackConfiguration config = trackPiece.getTrackConfiguration();
TrackConfiguration testConfig = TrackConfiguration.add(config,
direction);
if (trackRule.trackPieceIsLegal(testConfig)) {
possibleDirections.add(direction);
}
}
/* Put them into an array. */
targetInts = new int[possibleDirections.size()];
for (int i = 0; i < targetInts.length; i++) {
Step direction = possibleDirections.get(i);
PositionOnTrack targetPot = PositionOnTrack.createFacing(
targetPoint.x, targetPoint.y, direction);
targetInts[i] = targetPot.toInt();
}
} else {
/* If there is no track here, we can go in any direction. */
targetInts = new int[8];
for (int i = 0; i < 8; i++) {
PositionOnTrack targetPot = PositionOnTrack.createComingFrom(
targetPoint.x, targetPoint.y, Step.getInstance(i));
targetInts[i] = targetPot.toInt();
}
}
return targetInts;
}

equals

Class: jfreerails.util.Lists

Documentation

No documentation available

Source Code

@SuppressWarnings("unchecked")
public static boolean equals(List2D a, List2D b) {
if (a.sizeD1() != b.sizeD1())
return false;
for (int d1 = 0; d1 < a.sizeD1(); d1++) {
if (a.sizeD2(d1) != b.sizeD2(d1))
return false;
for (int d2 = 0; d2 < a.sizeD2(d1); d2++) {
if (!Utils.equal(a.get(d1, d2), b.get(d1, d2)))
return false;
}
}
return true;
}

testGet8And9bitTemplate

Class: jfreerails.world.track.TrackConfigurationTest

Documentation

No documentation available

Source Code

public void testGet8And9bitTemplate() {
for (int i = 0; i < 512; i++) {
TrackConfiguration tc = TrackConfiguration.from9bitTemplate(i);
assertEquals(i, tc.get9bitTemplate());
}
for (Step v : Step.getList()) {
TrackConfiguration tc = TrackConfiguration.getFlatInstance(v);
assertEquals(v.get9bitTemplate(), tc.get9bitTemplate());
assertEquals(v.get8bitTemplate(), tc.get8bitTemplate());
TrackConfiguration tc2 = TrackConfiguration.from9bitTemplate(v
.get9bitTemplate());
assertEquals(tc, tc2);
}
}

Track_TilesHandlerImpl

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public Track_TilesHandlerImpl(java.net.URL trackXmlUrl) {
try {
Track_TilesParser.parse(trackXmlUrl, this);
} catch (Exception e) {
e.printStackTrace();
}
}

main

Class: jfreerails.network.InetConnectionAccepter

Documentation

No documentation available

Source Code

public static void main(String[] args) {
try {
GameServer echoGameServer = EchoGameServer.startServer();
InetConnectionAccepter accepter = new InetConnectionAccepter(6666,
echoGameServer);
Thread t = new Thread(accepter);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}

removeLastD1

Class: jfreerails.util.List3D

Documentation

No documentation available

Source Code

void removeLastD1();

Called Methods

No outgoing method calls

getYScaleString

Class: jfreerails.client.view.NetWorthGraphJPanel

Documentation

No documentation available

Source Code

private String getYScaleString(long value) {
String abv;
if (value >= 1000000000) {
value = value / 1000000000;
abv = "b";
} else if (value >= 1000000) {
value = value / 1000000;
abv = "m";
} else if (value >= 1000) {
value = value / 1000;
abv = "k";
} else {
abv = "";
}
return "$" + String.valueOf(value) + abv;
}

Called Methods

No outgoing method calls

read

Class: jfreerails.network.AbstractInetConnection

Documentation

No documentation available

Source Code

FreerailsSerializable[] read() throws IOException {
if (status.isOpen()) {
return inbound.read();
}
throw new IOException();
}

processPendingElement

Class: jfreerails.util.ClassPath

Documentation

/**
* Clones the supplied list, then goes through it processing every element.
*
*/

Source Code

/**
* Clones the supplied list, then goes through it processing every element.
*
*/
protected LinkedList<String> processPendingElement(String pathElement) {
LinkedList<String> discoveredClasses = new LinkedList<String>();
File elementFile = new File(pathElement);
String elementName = elementFile.getAbsolutePath();
// do NOT process dupes
if (pathElementsThatHaveAlreadyBeenProcessed.contains(elementName))
return discoveredClasses;
try {
if (elementName.endsWith(".jar")) {
JarFile jar = null;
Manifest man = null;
jar = new JarFile(elementFile);
man = jar.getManifest();
// Find any nested path elements inside the JAR's own private
// class-path...
if (!(jarsThatHAveAlreadyBeenProcessed.contains(elementFile))) {
if (man != null) {
logger.fine("Jarfile = " + elementFile
+ " was not in jarsalreadydone (size = "
+ jarsThatHAveAlreadyBeenProcessed.size());
jarsThatHAveAlreadyBeenProcessed.add(elementFile);
List extraPathElements = findPathElementsInJar(man,
jar, elementFile);
logger.info("...[" + elementFile + "] contained "
+ extraPathElements.size()
+ " additional path elements");
for (Iterator iter = extraPathElements.iterator(); iter
.hasNext();) {
String element = (String) iter.next();
discoveredClasses
.addAll(processPendingElement(element));
}
}
// ...and add all the direct-listed classes that were in the
// JAR
Enumeration e = jar.entries();
while (e.hasMoreElements()) {
JarEntry entry = (JarEntry) e.nextElement();
if (!entry.isDirectory()
&& entry.getName().endsWith(".class")) {
String className = getClassNameFrom(entry.getName());
discoveredClasses.add(className);
}
}
}
} else if (elementName.endsWith(".zip")) {
discoveredClasses.addAll(getZipContents(elementFile));
} else if (elementName.endsWith(".class")) {
String className = convertToClass(elementFile);
discoveredClasses.add(className);
} else {
discoveredClasses.addAll(getDirectoryContents(elementFile));
}
// Mark this element as having been processed, and do NOT process
// dupes
pathElementsThatHaveAlreadyBeenProcessed.add(elementName);
} catch (Exception e) {
e.printStackTrace();
}
return discoveredClasses;
}

setHasSetupBeenCalled

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

protected void setHasSetupBeenCalled(boolean hasSetupBeenCalled) {
this.hasSetupBeenCalled = hasSetupBeenCalled;
}

Called Methods

No outgoing method calls

jButton1ActionPerformed

Class: jfreerails.client.view.SelectWagonsJPanel

Documentation

No documentation available

Source Code

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jButton1ActionPerformed
// Add your handling code here:
wagons.clear();
jLabel1.setText("");
this.repaint();
} // GEN-LAST:event_jButton1ActionPerformed

Called Methods

No outgoing method calls

equals

Class: jfreerails.network.specifics.SaveGameMessage2Server

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof SaveGameMessage2Server))
return false;
final SaveGameMessage2Server saveGameMessage2Server = (SaveGameMessage2Server) o;
if (id != saveGameMessage2Server.id)
return false;
if (!filename.equals(saveGameMessage2Server.filename))
return false;
return true;
}

Called Methods

No outgoing method calls

available

Class: jfreerails.util.CompressedInputStream

Documentation

No documentation available

Source Code

@Override
public int available() throws IOException {
if (maxReadIndex - readIndex == 0 && super.in.available() > 0
&& !readNextBuffer()) {
return -1;
}
return maxReadIndex - readIndex;
}

getLegalRoutes

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

public Step[] getLegalRoutes(Step directionComingFrom) {
// TODO add code..
return null;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.network.specifics.RefreshListOfGamesMessage2Server

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final RefreshListOfGamesMessage2Server other = (RefreshListOfGamesMessage2Server) obj;
if (id != other.id)
return false;
return true;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.network.specifics.LoadGameMessage2Server

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof LoadGameMessage2Server))
return false;
final LoadGameMessage2Server loadGameMessage2Server = (LoadGameMessage2Server) o;
if (id != loadGameMessage2Server.id)
return false;
if (!filename.equals(loadGameMessage2Server.filename))
return false;
return true;
}

Called Methods

No outgoing method calls

getBts

Class: jfreerails.client.renderer.BuildTrackController

Documentation

/** Utility method that gets the BuildTrackStrategy from the model root. */

Source Code

/** Utility method that gets the BuildTrackStrategy from the model root. */
private BuildTrackStrategy getBts() {
BuildTrackStrategy btss = (BuildTrackStrategy) modelRoot
.getProperty(ModelRoot.Property.BUILD_TRACK_STRATEGY);
if (null == btss)
throw new NullPointerException();
return btss;
}

hashCode

Class: jfreerails.controller.AddTrainPreMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = engineTypeId;
result = 29 * result + point.hashCode();
result = 29 * result + principal.hashCode();
result = 29 * result + schedule.hashCode();
return result;
}

RemoveCargoBundleMove

Class: jfreerails.move.RemoveCargoBundleMove

Documentation

No documentation available

Source Code

public RemoveCargoBundleMove(int i, ImmutableCargoBundle item,
FreerailsPrincipal p) {
super(KEY.CARGO_BUNDLES, i, item, p);
}

compareTo

Class: jfreerails.world.cargo.CargoBatch

Documentation

No documentation available

Source Code

public int compareTo(CargoBatch o) {
if (timeCreated != o.timeCreated)
return (int) (timeCreated - o.timeCreated);
if (cargoType != o.cargoType)
return (cargoType - o.cargoType);
if (stationOfOrigin != o.stationOfOrigin)
return (stationOfOrigin - o.stationOfOrigin);
if (sourceX != o.sourceX)
return (sourceX - o.sourceX);
if (sourceY != o.sourceY)
return (sourceY - o.sourceY);
return 0;
}

Called Methods

No outgoing method calls

convertPath2Points

Class: jfreerails.controller.TrackPathFinder

Documentation

No documentation available

Source Code

private List<ImPoint> convertPath2Points(IntArray path) {
PositionOnTrack progress = new PositionOnTrack();
List<ImPoint> proposedTrack = new ArrayList<ImPoint>();
ImPoint p;
for (int i = 0; i < path.size(); i++) {
progress.setValuesFromInt(path.get(i));
p = new ImPoint(progress.getX(), progress.getY());
proposedTrack.add(p);
logger.fine("Adding point " + p);
}
return proposedTrack;
}

createReportsMenu

Class: jfreerails.client.top.GUIComponentFactoryTestImpl

Documentation

No documentation available

Source Code

public JMenu createReportsMenu() {
return new JMenu("Reports");
}

Called Methods

No outgoing method calls

run

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public void run() {
status.open();
status.close();
}

ImInts

Class: jfreerails.world.common.ImInts

Documentation

No documentation available

Source Code

public ImInts(int... i) {
this.ints = i.clone();
}

Called Methods

  • _Dummy_.__Array__.clone (external)

getMultipleRuleInstance

Class: jfreerails.controller.BuildTrackStrategy

Documentation

No documentation available

Source Code

public static BuildTrackStrategy getMultipleRuleInstance(
ArrayList<Integer> ruleIDs, ReadOnlyWorld w) {
int[] rulesArray = generateRules(ruleIDs, w);
return new BuildTrackStrategy(rulesArray);
}

TrainModel

Class: jfreerails.world.train.TrainModel

Documentation

No documentation available

Source Code

public TrainModel(int engine, ImInts wagons, int scheduleID, int BundleId) {
engineTypeId = engine;
wagonTypes = wagons;
scheduleId = scheduleID;
cargoBundleId = BundleId;
}

Called Methods

No outgoing method calls

pullUp

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public void pullUp(int orderNumber) {
if (!canPullUp(orderNumber)) {
throw new IllegalArgumentException(String.valueOf(orderNumber));
}
boolean isGoingToThisStation = getOrderToGoto() == orderNumber;
TrainOrdersModel order = getOrder(orderNumber);
removeOrder(orderNumber);
addOrder(orderNumber - 1, order);
if (isGoingToThisStation) {
setOrderToGoto(orderNumber - 1);
}
}

equals

Class: jfreerails.move.ChangeItemInListMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof ChangeItemInListMove) {
ChangeItemInListMove test = (ChangeItemInListMove) o;
if (!before.equals(test.getBefore())) {
return false;
}
if (!after.equals(test.getAfter())) {
return false;
}
if (index != test.index) {
return false;
}
if (listKey != test.listKey) {
return false;
}
return true;
}
return false;
}

addNoBridgesButton

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

No documentation available

Source Code

private void addNoBridgesButton() {
JToggleButton toggleButton = new JToggleButton();
bridgeButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon("no_bridges"));
toggleButton.setPreferredSize(new java.awt.Dimension(36, 36));
toggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectionSet.put(TrackRule.TrackCategories.bridge, null);
setBuildTrackStrategy();
}
});
toggleButton.setToolTipText("Don't build bridges");
bridgesJPanel.add(toggleButton);
}

createGameMenu

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

public JMenu createGameMenu() {
sc = actionRoot.getServerControls();
JMenu gameMenu = new JMenu("Game");
gameMenu.setMnemonic(71);
JMenuItem quitJMenuItem = new JMenuItem("Exit Game");
quitJMenuItem.setMnemonic(88);
quitJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
final JMenu newGameJMenu = new JMenu(sc.getNewGameAction());
newGameJMenu.addMenuListener(new MenuListener() {
public void menuCanceled(MenuEvent e) {
}
public void menuDeselected(MenuEvent e) {
}
public void menuSelected(MenuEvent e) {
newGameJMenu.removeAll();
Enumeration<Action> actions = sc.getMapNames().getActions();
while (actions.hasMoreElements()) {
JMenuItem mi = new JMenuItem(actions.nextElement());
newGameJMenu.add(mi);
}
}
});
JMenuItem saveGameJMenuItem = new JMenuItem(sc.getSaveGameAction());
JMenuItem loadGameJMenuItem = new JMenuItem(sc.getLoadGameAction());
// Fix bug 1102806 Newspaper does nothing, so hide it.
// JMenuItem newspaperJMenuItem = new JMenuItem("Newspaper");
// newspaperJMenuItem.setMnemonic(78);
// newspaperJMenuItem.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// dialogueBoxController.showNewspaper("Headline");
// //glassPanel.setVisible(true);
// }
// });
// Set up the game speed sub-menu.
JMenu gameSpeedSubMenu = new JMenu("Game Speed");
ButtonGroup group = new ButtonGroup();
speedActions = sc.getSetTargetTickPerSecondActions();
Enumeration<MappedButtonModel> buttonModels = speedActions
.getButtonModels();
Enumeration<Action> actions = speedActions.getActions();
while (buttonModels.hasMoreElements()) {
JRadioButtonMenuItem mi = new JRadioButtonMenuItem(actions
.nextElement());
mi.setModel(buttonModels.nextElement());
group.add(mi);
gameSpeedSubMenu.add(mi);
}
gameMenu.add(newGameJMenu);
gameMenu.addSeparator();
gameMenu.add(loadGameJMenuItem);
gameMenu.add(saveGameJMenuItem);
gameMenu.addSeparator();
gameMenu.add(gameSpeedSubMenu);
// gameMenu.add(newspaperJMenuItem);
gameMenu.addSeparator();
gameMenu.add(quitJMenuItem);
if (CHEAT) {
/** For testing. */
final ActionListener build200trains = new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
WorldIterator wi = new NonNullElements(KEY.STATIONS,
modelRoot.getWorld(), modelRoot.getPrincipal());
if (wi.next()) {
Random randy = new Random();
StationModel station = (StationModel) wi.getElement();
ImList<PlannedTrain> before = station
.getProduction();
int numberOfEngineTypes = modelRoot.getWorld().size(
SKEY.ENGINE_TYPES) - 1;
int numberOfcargoTypes = modelRoot.getWorld().size(
SKEY.CARGO_TYPES) - 1;
PlannedTrain[] temp = new PlannedTrain[200];
for (int i = 0; i < temp.length; i++) {
int engineType = randy.nextInt(numberOfEngineTypes);
int[] wagonTypes = new int[] {
randy.nextInt(numberOfcargoTypes),
randy.nextInt(numberOfcargoTypes),
randy.nextInt(numberOfcargoTypes) };
PlannedTrain plannedTrain = new PlannedTrain(engineType, wagonTypes);
temp[i] = plannedTrain;
}
ImList<PlannedTrain> after = new ImList<PlannedTrain>(temp);
Move m = new ChangeProductionAtEngineShopMove(before,
after, wi.getIndex(), modelRoot.getPrincipal());
modelRoot.doMove(m);
}
}
};
JMenuItem build200TrainsMenuItem = new JMenuItem(
"Build 200 trains!");
build200TrainsMenuItem.addActionListener(build200trains);
gameMenu.add(build200TrainsMenuItem);
}
return gameMenu;
}

OverHeadTrainView

Class: jfreerails.client.view.OverHeadTrainView

Documentation

No documentation available

Source Code

public OverHeadTrainView(ReadOnlyWorld world, RenderersRoot rr, ModelRoot mr) {
this.w = world;
trainRenderer = new TrainRenderer(rr);
this.mr = mr;
}

Called Methods

No outgoing method calls

size

Class: jfreerails.world.cargo.MutableCargoBundle

Documentation

No documentation available

Source Code

public int size() {
return sortedMap.size();
}

Called Methods

No outgoing method calls

getBundles

Class: jfreerails.controller.DropOffAndPickupCargoMoveGenerator

Documentation

No documentation available

Source Code

private void getBundles() {
TrainModel trainModel = ((TrainModel) w.get(principal, KEY.TRAINS, trainId));
trainBundleId = trainModel.getCargoBundleID();
trainBefore = getCopyOfBundle(trainBundleId);
trainAfter = getCopyOfBundle(trainBundleId);
StationModel stationModel = ((StationModel) w.get(principal, KEY.STATIONS, stationId));
stationBundleId = stationModel.getCargoBundleID();
stationAfter = getCopyOfBundle(stationBundleId);
stationBefore = getCopyOfBundle(stationBundleId);
}

getStationRadius

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

public int getStationRadius() {
return this.properties.getStationRadius();
}

assertTryMoveIsOk

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

protected void assertTryMoveIsOk(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals("First try failed", MoveStatus.MOVE_OK, ms);
ms = m.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertEquals(
"Second try failed, this suggests that the tryDoMove method failed to leave the world unchanged!",
MoveStatus.MOVE_OK, ms);
}

getTotalDistance

Class: jfreerails.world.train.PathOnTiles

Documentation

/**
* Returns the distance you would travel if you walked the all the way along
* the path.
*/

Source Code

/**
* Returns the distance you would travel if you walked the all the way along
* the path.
*/
public double getTotalDistance() {
return getDistance(vectors.size());
}

handle_Consumes

Class: jfreerails.server.parser.CargoAndTerrainHandler

Documentation

/**
* An empty element event handling method.
*
*/

Source Code

/**
* An empty element event handling method.
*
*/
public void handle_Consumes(final Attributes meta) throws SAXException;

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.terrain.TileTypeImpl

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = consumption.hashCode();
result = 29 * result + conversion.hashCode();
result = 29 * result + production.hashCode();
result = 29 * result + rgb;
result = 29 * result + rightOfWay;
result = 29 * result + terrainCategory.hashCode();
result = 29 * result + terrainType.hashCode();
result = 29 * result
+ (tileBuildCost != null ? tileBuildCost.hashCode() : 0);
return result;
}

getDisplayName

Class: jfreerails.world.cargo.CargoType

Documentation

/** Returns the name, replacing any underscores with spaces. */

Source Code

/** Returns the name, replacing any underscores with spaces. */
public String getDisplayName() {
return this.name.replace('_', ' ');
}

Called Methods

No outgoing method calls

getPrice

Class: jfreerails.world.track.TrackRuleProperties

Documentation

No documentation available

Source Code

public Money getPrice() {
return price;
}

Called Methods

No outgoing method calls

sendCommand

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public void sendCommand(Message2Server c) {
if (null != serverCommandReceiver) {
serverCommandReceiver.sendCommand(c);
} else {
System.err.println(c.toString());
}
}

getSideOnImage

Class: jfreerails.client.renderer.TrainImages

Documentation

No documentation available

Source Code

public Image getSideOnImage() {
return sideOnImage;
}

Called Methods

No outgoing method calls

testCannotConnect2OtherRRsTrack

Class: jfreerails.move.ChangeTrackPieceCompositeMoveTest

Documentation

No documentation available

Source Code

public void testCannotConnect2OtherRRsTrack() {
assertFalse(ChangeTrackPieceMove.canConnect2OtherRRsTrack(world));
final int TRACK_RULE_ID = 0;
TrackRule trackRule = (TrackRule) getWorld().get(SKEY.TRACK_RULES,
TRACK_RULE_ID);
assertBuildTrackSucceeds(new ImPoint(0, 6), east, trackRule);
// Now change the owner of the track piece at (1, 6);
int anotherPlayer = 999;
FreerailsTile oldTile = (FreerailsTile) world.getTile(1, 6);
TrackPiece tp = oldTile.getTrackPiece();
TrackPiece newTrackPiece = new TrackPieceImpl(tp
.getTrackConfiguration(), tp.getTrackRule(), anotherPlayer,
TRACK_RULE_ID);
FreerailsTile newTile = FreerailsTile.getInstance(oldTile
.getTerrainTypeID(), newTrackPiece);
world.setTile(1, 6, newTile);
assertBuildTrackFails(new ImPoint(1, 6), east, trackRule);
world.setTile(1, 6, oldTile);
assertBuildTrackSucceeds(new ImPoint(1, 6), east, trackRule);
}

HtmlJPanel

Class: jfreerails.client.view.HtmlJPanel

Documentation

No documentation available

Source Code

HtmlJPanel() {
initComponents();
}

hashCode

Class: jfreerails.world.track.TrackRuleProperties

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = rGBvalue;
result = 29 * result + (enableDoubleTrack ? 1 : 0);
result = 29 * result + typeName.hashCode();
result = 29 * result + category.hashCode();
result = 29 * result + stationRadius;
result = 29 * result + price.hashCode();
result = 29 * result + fixedCost.hashCode();
result = 29 * result + maintenanceCost.hashCode();
return result;
}

isNewPlayersAllowed

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public boolean isNewPlayersAllowed() {
return newPlayersAllowed;
}

Called Methods

No outgoing method calls

handle_Converts

Class: jfreerails.server.parser.CargoAndTerrainHandlerImpl

Documentation

No documentation available

Source Code

public void handle_Converts(final Attributes meta) throws SAXException {
String inputCargo = meta.getValue("input");
String outputCargo = meta.getValue("output");
int input = string2CargoID(inputCargo);
int output = string2CargoID(outputCargo);
Conversion conversion = new Conversion(input, output);
typeConverts.add(conversion);
}

getSize4Panel

Class: experimental.TrackTilesGenerator

Documentation

No documentation available

Source Code

private Dimension getSize4Panel() {
int height = 90 * rules.size();
int width = 0;
int lastWidth = 0;
for (TrackRule rule : rules) {
width = Math.max(width, lastWidth);
lastWidth = 0;
Iterator<TrackConfiguration> it = rule
.getLegalConfigurationsIterator();
while (it.hasNext()) {
lastWidth += 60;
}
}
return new Dimension(width, height);
}

hashCode

Class: jfreerails.network.specifics.SetPropertyMessage2Client

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + key.hashCode();
result = 29 * result + value.hashCode();
return result;
}

Called Methods

No outgoing method calls

updateListOfFiles

Class: jfreerails.client.view.LoadGameJPanel

Documentation

No documentation available

Source Code

private void updateListOfFiles() {
ImStringList files = (ImStringList) modelRoot.getProperty(Property.SAVED_GAMES_LIST);
Object[] saves = new Object[files.size()];
for (int i = 0; i < files.size(); i++) {
saves[i] = files.get(i);
}
jList1.setListData(saves);
okButton.setEnabled(jList1.getSelectedIndex() != -1);
lastFiles = files;
}

isHit

Class: jfreerails.client.renderer.TrainRendererTest

Documentation

No documentation available

Source Code

public boolean isHit(Point wagonCenter, Point mouseClick, Step step) {
List<Map.Entry<Point, Step>> positions = new ArrayList<>();
positions.add(new AbstractMap.SimpleImmutableEntry<>(wagonCenter, step));
RenderersRoot rr = new MyRenderersRoot();
TrainModel train = new TrainModel(0);
TrainRenderer tr = new TrainRenderer(rr);
boolean hit = tr.isHit(mouseClick, train, positions);
return hit;
}

listUpdated

Class: jfreerails.client.view.TrainListCellRenderer

Documentation

No documentation available

Source Code

public void listUpdated(KEY key, int index, FreerailsPrincipal p) {
if (showingOrder) {
if (KEY.TRAIN_SCHEDULES == key && this.scheduleID == index) {
this.display(this.trainNumber, this.scheduleOrderNumber);
}
} else {
if (KEY.TRAINS == key && this.trainNumber == index) {
this.display(this.trainNumber);
}
}
}

testPopulateTokens2

Class: jfreerails.client.view.HtmlJPanelTest

Documentation

No documentation available

Source Code

public void testPopulateTokens2(){
String template = "Hey $a.name$ I would like you to meet $b.name$";
String expectedOutput = "Hey Tom I would like you to meet Claire";
Object objectContext = new Object() {
@SuppressWarnings("unused")
public Person a = new Person("Tom");
@SuppressWarnings("unused")
public Person b = new Person("Claire");
};
String output = HtmlJPanel.populateTokens(template, objectContext);
assertEquals(expectedOutput, output);
}

add

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

@SuppressWarnings("unchecked")
public void add(FreerailsPrincipal p, int index, Activity element) {
int playerIndex = p.getWorldIndex();
int lastID = activityLists.sizeD3(playerIndex, index) - 1;
ActivityAndTime last = activityLists.get(playerIndex, index, lastID);
double duration = last.act.duration();
double lastFinishTime = last.startTime + duration;
double thisStartTime = Math.max(lastFinishTime, currentTime()
.getTicks());
ActivityAndTime ant = new ActivityAndTime(element, thisStartTime);
activityLists.addD3(playerIndex, index, ant);
}

testChangingElementInList1

Class: jfreerails.move.WorldDiffsMoveTest

Documentation

No documentation available

Source Code

public void testChangingElementInList1() {
world.add(fp1, KEY.STATIONS, city1);
world.add(fp1, KEY.STATIONS, city1);
diffs.set(fp1, KEY.STATIONS, 0, city2);
diffs.set(fp1, KEY.STATIONS, 1, city2);
runTests();
}

testAddD3

Class: jfreerails.util.List3DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List3DDiff.addD3(int, int, T)'
*/
public void testAddD3() {
underlying.addD1();
underlying.addD1();
underlying.addD2(1);
underlying.addD2(1);
diffs.addD3(1, 0, new Integer(5));
assertEquals(1, diffs.sizeD3(1, 0));
diffs.addD3(1, 1, new Integer(5));
assertEquals(1, diffs.sizeD3(1, 1));
}

getCategory

Class: jfreerails.world.cargo.Categories

Documentation

No documentation available

Source Code

public static Categories getCategory(String cat) {
for (Categories cmp : values()) {
if (cmp.toString().equals(cat)) {
return cmp;
}
}
throw new IllegalArgumentException("Category:" + cat + " unknown.");
}

Called Methods

  • jfreerails.world.cargo.CargoType.Categories.values (external)

testAddingActivity

Class: jfreerails.move.WorldDiffsMoveTest

Documentation

No documentation available

Source Code

public void testAddingActivity(){
Activity act = new TestActivity(30);
int row = world.addActiveEntity(fp1, act);
act = new TestActivity(40);
world.add(fp1, row, act);
act = new TestActivity(50);
diffs.add(fp1, row, act);
runTests();
}

toImmutableCargoBundle

Class: jfreerails.world.cargo.MutableCargoBundle

Documentation

No documentation available

Source Code

public ImmutableCargoBundle toImmutableCargoBundle() {
return new ImmutableCargoBundle(sortedMap);
}

Called Methods

No outgoing method calls

isConfirmed

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

boolean isConfirmed(int player) {
logger.fine("confirmedPlayers.size()=" + confirmedPlayers.size());
boolean isConfirmed = confirmedPlayers.contains(players.get(player));
return isConfirmed;
}

Called Methods

No outgoing method calls

duration

Class: jfreerails.world.common.Activity

Documentation

No documentation available

Source Code

double duration();

Called Methods

No outgoing method calls

main

Class: experimental.ConnectAllCities

Documentation

/**
* @param args the command line arguments
*/

Source Code

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException, PathNotFoundException {
SavedGamesManager gamesManager = new SavedGamesManagerImpl();
String[] newMapNames = gamesManager.getNewMapNames();
World w = (World) gamesManager.newMap(newMapNames[0]);
System.out.println(w.getClass());
ServerGameModel gameModel = new ServerGameModelImpl();
String name = "Tester";
Player p = new Player(name, 0);
Move addPlayerMove = AddPlayerMove.generateMove(w, p);
MoveStatus ms = addPlayerMove.doMove(w, Player.AUTHORITATIVE);
w.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
w.setTime(new GameTime(0));
w.set(ITEM.GAME_SPEED, new GameSpeed(10));
w.set(ITEM.GAME_RULES, GameRules.DEFAULT_RULES);
Transaction t = new AddItemTransaction(Transaction.Category.BOND, 0, 1, new Money(50000000));
w.addTransaction(p.getPrincipal(), t);
List<CityModel> citiesUnconnected = new ArrayList<>();
List<CityModel> citiesConnected = new ArrayList<>();
int nCities = w.size(SKEY.CITIES);
System.out.format("There are %d cities.%n", nCities);
for (int i = 0; i < nCities; i++) {
citiesUnconnected.add((CityModel) w.get(SKEY.CITIES, i));
}
CityModel cityA = citiesUnconnected.remove(0);
citiesConnected.add(cityA);
DistanceComparator distanceComparator = new DistanceComparator(cityA.getCityX(), cityA.getCityY());
Collections.sort(citiesUnconnected, distanceComparator);
MapCustomizer mc = new MapCustomizer(w);
int n = citiesUnconnected.size();
for (int i = 0; i < n; i++) {
CityModel cityB = citiesUnconnected.remove(0);
System.out.format("build track to %s%n", cityB.getCityName());
distanceComparator = new DistanceComparator(cityB.getCityX(), cityB.getCityY());
Collections.sort(citiesConnected, distanceComparator);
ImPoint b = cityB.getLocation();
for (int j = 0; j < Math.min(3, citiesConnected.size()); j++) {
cityA = citiesConnected.get(j);
ImPoint a = cityA.getLocation();
mc.buildTrack(a, b);
try {
if (j == 0) {
if (i == 0) {
mc.buildStation(a);
}
mc.buildStation(b);
}
} catch (java.lang.IllegalStateException e) {
//sometimes it is not possible to build the
//stations, e.g. another one is too close.
break;
}
int stationA = mc.getStationId(a);
int stationB = mc.getStationId(b);
if (stationA >= 0 && stationB >= 0) {
//the stations exist.
mc.buildTrain(b, stationA, stationB);
}
}
System.out.format("There are %d stations%n", w.size(p.getPrincipal(), KEY.STATIONS));
citiesConnected.add(cityB);
}
System.out.println(ms);
String[] passwords = {"password"};
gameModel.setWorld(w, passwords);
gamesManager.saveGame(gameModel, "generated.sav");
}

waitForObjectFromClient

Class: jfreerails.network.InetConnection2Client

Documentation

No documentation available

Source Code

public FreerailsSerializable waitForObjectFromClient() throws IOException,
InterruptedException {
return waitForObject();
}

testTryDoMove

Class: jfreerails.move.ChangeTrackPieceMoveTest

Documentation

No documentation available

Source Code

public void testTryDoMove() {
setUp();
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
TrackConfiguration newConfig;
TrackMove move;
MoveStatus moveStatus;
// Try building the simplest piece of track.
newConfig = TrackConfiguration.getFlatInstance("000010000");
oldTrackPiece = ((FreerailsTile) getWorld().getTile(0, 0)).getTrackPiece();
final int trackRuleID = 0;
final TrackRule r = (TrackRule) getWorld().get(SKEY.TRACK_RULES,
trackRuleID);
newTrackPiece = new TrackPieceImpl(newConfig, r, 0, trackRuleID);
move = new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece,
new ImPoint(0, 0));
moveStatus = move.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(moveStatus);
assertEquals(true, moveStatus.isOk());
// As above but with newTrackPiece and oldTrackPiece in the wrong order,
// should fail.
move = new ChangeTrackPieceMove(newTrackPiece, oldTrackPiece,
new ImPoint(0, 0));
moveStatus = move.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(moveStatus);
assertEquals(false, moveStatus.isOk());
// Try a move that does nothing, i.e. oldTrackPiece==newTrackPiece,
// should fail.
move = new ChangeTrackPieceMove(oldTrackPiece, oldTrackPiece,
new ImPoint(0, 0));
moveStatus = move.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(moveStatus);
assertEquals(false, moveStatus.isOk());
// Try buildingtrack outside the map.
move = new ChangeTrackPieceMove(newTrackPiece, oldTrackPiece,
new ImPoint(100, 0));
moveStatus = move.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(moveStatus);
assertEquals(false, moveStatus.isOk());
// Try building an illegal track configuration.
newConfig = TrackConfiguration.getFlatInstance("000011111");
newTrackPiece = new TrackPieceImpl(newConfig, r, 0, trackRuleID);
move = new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece,
new ImPoint(0, 0));
moveStatus = move.tryDoMove(getWorld(), Player.AUTHORITATIVE);
assertEquals(false, moveStatus.isOk());
}

TrainCrashException

Class: jfreerails.move.TrainCrashException

Documentation

No documentation available

Source Code

public TrainCrashException(int aTrain, int bTrain) {
trainA = aTrain;
trainB = bTrain;
}

Called Methods

No outgoing method calls

TransactionAggregator

Class: jfreerails.world.top.TransactionAggregator

Documentation

No documentation available

Source Code

public TransactionAggregator(ReadOnlyWorld w, FreerailsPrincipal principal) {
this.w = w;
this.principal = principal;
}

Called Methods

No outgoing method calls

start_CanOnlyBuildOnTheseTerrainTypes

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* A container element start event handling method.
*
* @param meta
* attributes
*/

Source Code

/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_CanOnlyBuildOnTheseTerrainTypes(final Attributes meta)
throws SAXException;

Called Methods

No outgoing method calls

writeAllImages

Class: jfreerails.client.common.ImageManagerImpl

Documentation

No documentation available

Source Code

public void writeAllImages() throws IOException {
for (String s : imageHashMap.keySet()) {
writeImage(s);
}
}

resetGraphics

Class: jfreerails.client.renderer.BufferedTiledBackgroundRenderer

Documentation

/** When the VolatileImage is created or restored, we need to (re)create the
Graphics objects.
*/

Source Code

/** When the VolatileImage is created or restored, we need to (re)create the
Graphics objects.
*/
private void resetGraphics() {
if (bg != null) {
bg.dispose();
}
bg = backgroundBuffer.getGraphics();
if (translatedBg != null) {
translatedBg.dispose();
}
translatedBg = bg.create();
translatedBg.translate(-bufferRect.x, -bufferRect.y);
}

Called Methods

No outgoing method calls

getCargoBundleID

Class: jfreerails.world.station.StationModel

Documentation

No documentation available

Source Code

public int getCargoBundleID() {
return cargoBundleNumber;
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.network.specifics.NameAndPassword

Documentation

No documentation available

Source Code

@Override
public String toString() {
return username;
}

Called Methods

No outgoing method calls

tilesChanged

Class: jfreerails.world.top.WorldMapListener

Documentation

/**
* Called when tiles have changed.
*
* @param tilesChanged
* rectangle containing the tiles that have change; all the
* points contained by the rectangle must be within the map's
* bounds.
*/

Source Code

/**
* Called when tiles have changed.
*
* @param tilesChanged
* rectangle containing the tiles that have change; all the
* points contained by the rectangle must be within the map's
* bounds.
*/
void tilesChanged(Rectangle tilesChanged);

Called Methods

No outgoing method calls

handle_LegalRouteAcrossNode

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void handle_LegalRouteAcrossNode(final Attributes meta)
throws SAXException {
}

Called Methods

No outgoing method calls

setNextEnabled

Class: jfreerails.launcher.Launcher

Documentation

No documentation available

Source Code

public void setNextEnabled(boolean enabled) {
nextButton.setEnabled(enabled);
if (nextIsStart) {
nextButton.setText("Start");
} else {
nextButton.setText("Next...");
}
}

Called Methods

No outgoing method calls

condition

Class: jfreerails.controller.NetWorthCalculator

Documentation

No documentation available

Source Code

@Override
protected boolean condition(int transactionID) {
Transaction t = super.w.getTransaction(super.principal,
transactionID);
if (t instanceof AddItemTransaction) {
if(t.getCategory().equals(Transaction.Category.ISSUE_STOCK)){
return true;
}
// Since buying something is just converting one asset type to
// another.
return false;
}
return true;
}

getTrackGraphicID

Class: jfreerails.world.track.NullTrackPiece

Documentation

No documentation available

Source Code

public int getTrackGraphicID() {
return 0;
}

Called Methods

No outgoing method calls

compareTo

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

public int compareTo(TrackRule arg0) {
// TODO Auto-generated method stub
return 0;
}

Called Methods

No outgoing method calls

testMove

Class: jfreerails.move.ChangeTrackPieceMoveTest

Documentation

No documentation available

Source Code

@Override
public void testMove() {
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
TrackConfiguration newConfig;
newConfig = TrackConfiguration.getFlatInstance("000010000");
oldTrackPiece = ((FreerailsTile) getWorld().getTile(0, 0)).getTrackPiece();
TrackRule r = (TrackRule) getWorld().get(SKEY.TRACK_RULES, 0);
newTrackPiece = new TrackPieceImpl(newConfig, r, 0, 0);
Move move = new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece,
new ImPoint(0, 0));
assertSurvivesSerialisation(move);
assertOkButNotRepeatable(move);
}

testAddD1

Class: jfreerails.util.List3DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List3DDiff.addD1()'
*/
public void testAddD1() {
diffs.addD1();
assertEquals(1, diffs.sizeD1());
diffs.addD1();
assertEquals(2, diffs.sizeD1());
}

getArray

Class: jfreerails.util.GrowableBase

Documentation

/**
* Get the backing array. This method is used by the type-agnostic base
* class code to access the array used for type-specific storage by the
* child class.
*
* @return backing array object
*/

Source Code

/**
* Get the backing array. This method is used by the type-agnostic base
* class code to access the array used for type-specific storage by the
* child class.
*
* @return backing array object
*/
protected abstract Object getArray();

Called Methods

No outgoing method calls

getName

Class: jfreerails.world.train.WagonType

Documentation

No documentation available

Source Code

public String getName() {
return typeName;
}

Called Methods

No outgoing method calls

initComponents

Class: jfreerails.client.view.BrokerJFrame

Documentation

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/

Source Code

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
jScrollPane1 = new javax.swing.JScrollPane();
jPanel1 = new javax.swing.JPanel();
htmlJLabel = new javax.swing.JLabel();
done = new javax.swing.JButton();
brokerMenu = new javax.swing.JMenuBar();
bonds = new javax.swing.JMenu();
issueBond = new javax.swing.JMenuItem();
repayBond = new javax.swing.JMenuItem();
stocks = new javax.swing.JMenu();
getContentPane().setLayout(new java.awt.GridBagLayout());
jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
jPanel1.setLayout(new java.awt.BorderLayout());
htmlJLabel.setFont(new java.awt.Font("Dialog", 0, 12));
htmlJLabel.setText("sdfa");
htmlJLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
htmlJLabel.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
jPanel1.add(htmlJLabel, java.awt.BorderLayout.CENTER);
jScrollPane1.setViewportView(jPanel1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(jScrollPane1, gridBagConstraints);
done.setText("Close");
done.setVerifyInputWhenFocusTarget(false);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
getContentPane().add(done, gridBagConstraints);
bonds.setText("Bonds");
issueBond.setText("Issue Bond");
bonds.add(issueBond);
repayBond.setText("Repay Bond");
bonds.add(repayBond);
brokerMenu.add(bonds);
stocks.setText("Stocks");
brokerMenu.add(stocks);
setJMenuBar(brokerMenu);
pack();
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.util.List1DDiff

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object obj) {
if (!(obj instanceof List1D))
return false;
return Lists.equals(this, (List1D) obj);
}

getScale

Class: jfreerails.client.view.DetailMapRenderer

Documentation

No documentation available

Source Code

public float getScale() {
return Constants.TILE_SIZE;
}

Called Methods

No outgoing method calls

exitFullScreenMode

Class: jfreerails.controller.ScreenHandler

Documentation

No documentation available

Source Code

public synchronized static void exitFullScreenMode(){
device.setFullScreenWindow(null);
}

Called Methods

No outgoing method calls

getAmount

Class: jfreerails.world.cargo.CargoBundle

Documentation

No documentation available

Source Code

int getAmount(int cargoType);

Called Methods

No outgoing method calls

getTimeCreated

Class: jfreerails.world.cargo.CargoBatch

Documentation

No documentation available

Source Code

public long getTimeCreated() {
return timeCreated;
}

Called Methods

No outgoing method calls

getTrackGraphicsID

Class: jfreerails.world.track.TrackConfiguration

Documentation

No documentation available

Source Code

public int getTrackGraphicsID() {
return configuration;
}

Called Methods

No outgoing method calls

add

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public int add(SKEY key, FreerailsSerializable element) {
return sharedLists.addD2(key.getKeyID(), element);
}

StockTransaction

Class: jfreerails.world.accounts.StockTransaction

Documentation

No documentation available

Source Code

private StockTransaction(Category category, int playerId, int quantity,
Money amount) {
super(category, playerId, quantity, amount);
if (playerId < 0)
throw new IllegalArgumentException();
}

tearDown

Class: jfreerails.network.specifics.AbstractFreerailsServerTestCase

Documentation

No documentation available

Source Code

@Override
protected synchronized void tearDown() throws Exception {
connectionAccepter.stop();
}

removeAllWagons

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void removeAllWagons() {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
newOrders = new TrainOrdersModel(oldOrders.getStationID(),
new ImInts(), false, false);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}

tryDoMove

Class: jfreerails.controller.MoveExecutor

Documentation

No documentation available

Source Code

MoveStatus tryDoMove(Move m);

Called Methods

No outgoing method calls

testNext

Class: jfreerails.world.top.NonNullElementsTest

Documentation

No documentation available

Source Code

public void testNext() {
WorldIterator wi = new NonNullElements(KEY.STATIONS, w,
MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(WorldIterator.BEFORE_FIRST, wi.getRowID());
assertEquals(WorldIterator.BEFORE_FIRST, wi.getIndex());
// Look at first station
boolean b = wi.next();
assertTrue(b);
int index = wi.getIndex();
assertEquals(0, index);
assertEquals(0, wi.getRowID());
assertEquals(station1, wi.getElement());
// Look at second station
assertTrue(wi.next());
assertEquals(2, wi.getIndex());
assertEquals(1, wi.getRowID());
assertEquals(station2, wi.getElement());
WorldIterator wi2 = new NonNullElements(SKEY.TRACK_RULES, w);
assertTrue(!wi2.next());
}

itemAdded

Class: jfreerails.client.view.TrainListCellRenderer

Documentation

No documentation available

Source Code

public void itemAdded(KEY key, int index, FreerailsPrincipal p) {
}

Called Methods

No outgoing method calls

getHeight

Class: jfreerails.client.view.TrainListCellRenderer

Documentation

No documentation available

Source Code

@Override
public int getHeight() {
return height;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.move.AddItemToSharedListMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = listKey.hashCode();
result = 29 * result + index;
result = 29 * result + (item != null ? item.hashCode() : 0);
return result;
}

Called Methods

No outgoing method calls

getBestDisplayMode

Class: jfreerails.controller.ScreenHandler

Documentation

No documentation available

Source Code

private static DisplayMode getBestDisplayMode() {
for (int x = 0; x < BEST_DISPLAY_MODES.length; x++) {
DisplayMode[] modes = device.getDisplayModes();
for (int i = 0; i < modes.length; i++) {
if (modes[i].getWidth() == BEST_DISPLAY_MODES[x].getWidth()
&& modes[i].getHeight() == BEST_DISPLAY_MODES[x]
.getHeight()
&& modes[i].getBitDepth() == BEST_DISPLAY_MODES[x]
.getBitDepth()) {
logger.fine("Best display mode is "
+ (new MyDisplayMode(BEST_DISPLAY_MODES[x]))
.toString());
return BEST_DISPLAY_MODES[x];
}
}
}
return null;
}

isWaitingForFullLoad

Class: jfreerails.move.TransferCargoAtStationMove

Documentation

No documentation available

Source Code

public boolean isWaitingForFullLoad() {
return waitingForFullLoad;
}

Called Methods

No outgoing method calls

nextEdge

Class: jfreerails.controller.BuildTrackExplorer

Documentation

No documentation available

Source Code

public void nextEdge() {
if (!hasNextEdge()) {
throw new NoSuchElementException();
}
// The direction we are moving relative to the current position.
Step direction = Step.getInstance(directionInt);
currentBranch.setCameFrom(direction);
currentBranch.setX(currentPosition.getX() + direction.getDx());
currentBranch.setY(currentPosition.getY() + direction.getDy());
directionInt++;
beforeFirst = false;
}

getMoveFork

Class: jfreerails.network.specifics.FreerailsClient

Documentation

No documentation available

Source Code

public final MoveChainFork getMoveFork() {
return moveFork;
}

Called Methods

No outgoing method calls

ConfirmExitJPanel

Class: jfreerails.client.view.ConfirmExitJPanel

Documentation

/** Creates new form ConfirmExitJPanel. */

Source Code

/** Creates new form ConfirmExitJPanel. */
public ConfirmExitJPanel() {
initComponents();
}

testConnecting

Class: jfreerails.network.EchoGameServerTest

Documentation

/**
* Tests connecting to an EchoGameServer using instances of
* InetConnection2Server.
*/

Source Code

/**
* Tests connecting to an EchoGameServer using instances of
* InetConnection2Server.
*/
public void testConnecting() {
try {
assertEquals(0, echoGameServer.countOpenConnections());
InetConnection2Server con1 = new InetConnection2Server(ipAddress,
server.getLocalPort());
InetConnection2Server con2 = new InetConnection2Server(ipAddress,
server.getLocalPort());
assertEquals(2, echoGameServer.countOpenConnections());
con1.writeToServer(new Money(99));
con1.flush();
FreerailsSerializable fs = con2.waitForObject();
assertEquals(new Money(99), fs);
} catch (Exception e) {
e.printStackTrace();
fail();
}
}

setBuildTrackStrategy

Class: jfreerails.controller.TrackMoveProducer

Documentation

No documentation available

Source Code

public void setBuildTrackStrategy(BuildTrackStrategy buildTrackStrategy) {
mr.setProperty(Property.BUILD_TRACK_STRATEGY, buildTrackStrategy);
}

handle_TerrainType

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* An empty element event handling method.
*/

Source Code

/**
* An empty element event handling method.
*/
void handle_TerrainType(final Attributes meta) throws SAXException;

Called Methods

No outgoing method calls

getTileIcons

Class: jfreerails.client.renderer.AbstractTileRenderer

Documentation

No documentation available

Source Code

Image[] getTileIcons() {
return tileIcons;
}

Called Methods

No outgoing method calls

ChangeTrackPieceCompositeMoveTest

Class: jfreerails.move.ChangeTrackPieceCompositeMoveTest

Documentation

No documentation available

Source Code

public ChangeTrackPieceCompositeMoveTest(java.lang.String testName) {
super(testName);
}

getMove

Class: jfreerails.move.TimeTickMove

Documentation

No documentation available

Source Code

public static TimeTickMove getMove(ReadOnlyWorld w) {
GameTime oldTime = w.currentTime();
GameTime newTime = new GameTime(oldTime.getTicks() + 1);
return new TimeTickMove(oldTime, newTime);
}

hasNextEdge

Class: jfreerails.controller.BuildTrackExplorer

Documentation

No documentation available

Source Code

public boolean hasNextEdge() {
while (directionInt < 8) {
if (canBuildTrack()) {
return true;
}
directionInt++;
}
return false;
}

size

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public int size(SKEY key) {
return sharedLists.sizeD2(key.getKeyID());
}

equals

Class: jfreerails.world.cargo.CargoBatch

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof CargoBatch) {
CargoBatch test = (CargoBatch) o;
if (test.getCargoType() == this.cargoType
&& test.getSourceX() == this.sourceX
&& test.sourceY == this.sourceY
&& test.timeCreated == this.timeCreated
&& test.stationOfOrigin == this.stationOfOrigin) {
return true;
}
return false;
}
return false;
}

setup

Class: jfreerails.controller.TrainStopsHandlerTest

Documentation

No documentation available

Source Code

@Before
public void setup() throws Exception {
MapCustomizer mc = new MapCustomizer();
ImPoint a = new ImPoint(10, 10);
ImPoint b = new ImPoint(20, 20);
mc.buildTrack(a, b).buildStation(a).buildStation(b);
mc.buildTrain(a, 0, 0);
w = mc.w;
}

testGetUnderlyingSize

Class: jfreerails.util.List3DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List3DDiff.getUnderlyingSize(int...)'
*/
public void testGetUnderlyingSize() {
assertEquals(-1, diffs.getUnderlyingSize(0,0));
assertEquals(-1, diffs.getUnderlyingSize(0));
assertEquals(0, diffs.getUnderlyingSize());
assertEquals(-1, diffs.getUnderlyingSize(1, 0));
assertEquals(-1, diffs.getUnderlyingSize(0, 1));
underlying.addD1();
underlying.addD1();
assertEquals(2, diffs.getUnderlyingSize());
assertEquals(0, diffs.getUnderlyingSize(1));
assertEquals(0, diffs.getUnderlyingSize(0));
}

getStationId

Class: jfreerails.world.accounts.DeliverCargoReceipt

Documentation

No documentation available

Source Code

public int getStationId() {
return stationId;
}

Called Methods

No outgoing method calls

setInfoText

Class: jfreerails.launcher.Launcher

Documentation

No documentation available

Source Code

public void setInfoText(String text, int status) {
infoLabel.setText(text);
switch (status) {
case LauncherInterface.ERROR:
infoLabel.setIcon(errorIcon);
nextButton.setEnabled(false);
break;
case LauncherInterface.INFO:
infoLabel.setIcon(infoIcon);
nextButton.setEnabled(true);
break;
case LauncherInterface.WARNING:
infoLabel.setIcon(warningIcon);
nextButton.setEnabled(true);
break;
default:
throw new IllegalArgumentException(String.valueOf(status));
}
}

Called Methods

No outgoing method calls

ChangeGameSpeedMove

Class: jfreerails.move.ChangeGameSpeedMove

Documentation

No documentation available

Source Code

private ChangeGameSpeedMove(GameSpeed before, GameSpeed after) {
oldSpeed = before;
newSpeed = after;
}

Called Methods

No outgoing method calls

open

Class: jfreerails.network.AbstractInetConnection

Documentation

No documentation available

Source Code

private synchronized void open() throws IOException {
Thread t = new Thread(this);
t.setName(getThreadName());
inetConnection.open();
t.start();
readerThreadStatus.open();
}

getEngineImages

Class: jfreerails.client.top.RenderersRootImpl

Documentation

No documentation available

Source Code

public TrainImages getEngineImages(int type) {
return engineImages.get(type);
}

Called Methods

No outgoing method calls

paintComponent

Class: jfreerails.client.view.BalanceSheetHtmlJPanel

Documentation

No documentation available

Source Code

@Override
protected void paintComponent(Graphics g) {
/* Check to see if the text needs updating before painting. */
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
int currentNumberOfTransactions = world
.getNumberOfTransactions(playerPrincipal);
if (currentNumberOfTransactions != lastNumTransactions) {
updateHtml();
}
super.paintComponent(g);
}

sendWorldUpdatedCommand

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

private void sendWorldUpdatedCommand() {
/* Send the world to the clients. */
confirmationID = getNextClientCommandId();
SetWorldMessage2Client command = new SetWorldMessage2Client(
confirmationID, getWorld());
send2All(command);
}

write

Class: jfreerails.util.CompressedOutputStream

Documentation

No documentation available

Source Code

@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}

sendItemAdded

Class: jfreerails.network.specifics.MoveChainFork

Documentation

No documentation available

Source Code

private void sendItemAdded(KEY key, int index, FreerailsPrincipal p) {
for (int i = 0; i < listListeners.size(); i++) {
WorldListListener l = listListeners.get(i);
l.itemAdded(key, index, p);
}
}

setFocusableFalse

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

/** Calls setFocusable(false) for each button in the button group. */

Source Code

/** Calls setFocusable(false) for each button in the button group. */
private void setFocusableFalse(ButtonGroup bg) {
for (Enumeration<AbstractButton> buttons = bg.getElements(); buttons
.hasMoreElements();) {
buttons.nextElement().setFocusable(false);
}
}

Called Methods

No outgoing method calls

calcS

Class: jfreerails.world.train.SpeedAgainstTime

Documentation

/**
* Returns the distance travelled at time t. The returned value, s,
* satisfies the following conditions:
* <ol>
* <li>s >= 0</li>
* <li>s <= getS()</li>
* <li>s = 0 if t = 0 </li>
* <li>s = getS() if t = getT()</li>
* </ol>
*
* @throws IllegalArgumentException
* iff t < 0 or t > getT()
* @return s
*/

Source Code

/**
* Returns the distance travelled at time t. The returned value, s,
* satisfies the following conditions:
* <ol>
* <li>s >= 0</li>
* <li>s <= getS()</li>
* <li>s = 0 if t = 0 </li>
* <li>s = getS() if t = getT()</li>
* </ol>
*
* @throws IllegalArgumentException
* iff t < 0 or t > getT()
* @return s
*/
double calcS(double t);

Called Methods

No outgoing method calls

getTerrainType

Class: jfreerails.client.renderer.AbstractTileRenderer

Documentation

No documentation available

Source Code

String getTerrainType() {
return tileModel.getTerrainTypeName();
}

removeLastTransaction

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public Transaction removeLastTransaction(FreerailsPrincipal p) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = bankAccounts.removeLastD2(playerIndex);
Money oldBalance = currentBalance.get(playerIndex);
Money newBalance = new Money(oldBalance.getAmount()
- tats.getT().deltaCash().getAmount());
currentBalance.set(playerIndex, newBalance);
return tats.getT();
}

TrackMaintenanceMoveGenerator

Class: jfreerails.server.TrackMaintenanceMoveGenerator

Documentation

No documentation available

Source Code

public TrackMaintenanceMoveGenerator(MoveReceiver mr) {
this.moveReceiver = mr;
}

Called Methods

No outgoing method calls

getPrice

Class: jfreerails.world.track.TrackRule

Documentation

No documentation available

Source Code

Money getPrice();

Called Methods

No outgoing method calls

setUp

Class: jfreerails.network.LocalConnectionTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
localConnection = new LocalConnection();
}

Called Methods

No outgoing method calls

getMapDiffs

Class: jfreerails.world.top.WorldDiffs

Documentation

/**
* The iterator returns instances of java.awt.Point that store the
* coordinates of tiles that are different to the underlying world object.
*/

Source Code

/**
* The iterator returns instances of java.awt.Point that store the
* coordinates of tiles that are different to the underlying world object.
*/
public Iterator<ImPoint> getMapDiffs() {
return mapDiff.keySet().iterator();
}

Called Methods

No outgoing method calls

test3

Class: jfreerails.network.specifics.MovePrecommitterTest

Documentation

/** Test test rejection 1. */

Source Code

/** Test test rejection 1. */
public void test3() {
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
assertFalse(oldtime.equals(newTime));
Move m = new TimeTickMove(oldtime, newTime);
MoveStatus ms = m.tryDoMove(w, Player.AUTHORITATIVE);
assertTrue(ms.ok);
committer.toServer(m);
/* The move m should now have been precommitted. */
assertEquals(newTime, getTime());
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(1, committer.precomitted.size());
/* Now, suppose the server rejected the move.. */
MoveStatus rejection = MoveStatus.moveFailed("Rejected!");
committer.fromServer(rejection);
assertEquals(oldtime, getTime());
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
}

contains

Class: jfreerails.world.cargo.MutableCargoBundle

Documentation

No documentation available

Source Code

public boolean contains(CargoBatch cb) {
return sortedMap.containsKey(cb);
}

Called Methods

No outgoing method calls

set

Class: jfreerails.util.List3DImpl

Documentation

No documentation available

Source Code

public void set(int d1, int d2, int d3, T element) {
ArrayList<T> dim3 = elementData.get(d1).get(d2);
dim3.set(d3, element);
}

Called Methods

No outgoing method calls

test1

Class: jfreerails.network.specifics.MovePrecommitterTest

Documentation

/** Test simple case of precommitting then fully committing moves. */

Source Code

/** Test simple case of precommitting then fully committing moves. */
public void test1() {
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
assertFalse(oldtime.equals(newTime));
Move m = new TimeTickMove(oldtime, newTime);
MoveStatus ms = m.tryDoMove(w, Player.AUTHORITATIVE);
assertTrue(ms.ok);
committer.toServer(m);
/* The move m should now have been precommitted. */
assertEquals(newTime, getTime());
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(1, committer.precomitted.size());
committer.fromServer(ms);
/* The move m should now be full committed. */
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
assertEquals(newTime, getTime());
}

test1

Class: jfreerails.world.train.MutableScheduleTest

Documentation

No documentation available

Source Code

public void test1() {
TrainOrdersModel order0 = new TrainOrdersModel(0, null, false, false);
TrainOrdersModel order1 = new TrainOrdersModel(1, null, false, false);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
int station2Goto = s.getStationToGoto();
assertEquals(0, station2Goto);
// ImmutableSchedule is = s.toImmutableSchedule();
//
// int i = is.getStationToGoto();
}

getId

Class: jfreerails.world.player.PlayerPrincipal

Documentation

/**
* @return an integer unique to this PlayerPrincipal
*/

Source Code

/**
* @return an integer unique to this PlayerPrincipal
*/
public int getId() {
return id;
}

Called Methods

No outgoing method calls

getImage

Class: jfreerails.client.common.ImageManagerImpl

Documentation

No documentation available

Source Code

public Image getImage(String relativeFilename) throws IOException {
relativeFilename = relativeFilename.replace(' ', '_');
if (!isValid(relativeFilename))
throw new IllegalArgumentException(relativeFilename
+ " must match " + A_REGEX);
if (imageHashMap.containsKey(relativeFilename)) {
return imageHashMap.get(relativeFilename);
}
// File f = new File(pathToReadFrom+File.separator+relativeFilename);
String read = pathToReadFrom + relativeFilename;
read = read.replace(File.separatorChar, '/');
URL url = ImageManagerImpl.class.getResource(read);
if (null == url) {
throw new IOException("Couldn't find: " + read);
}
Image tempImage = ImageIO.read(url);
if (null == tempImage) {
throw new IOException("Couldn't find: " + read);
}
Image compatibleImage = defaultConfiguration.createCompatibleImage(
tempImage.getWidth(null), tempImage.getHeight(null),
Transparency.TRANSLUCENT);
Graphics g = compatibleImage.getGraphics();
g.drawImage(tempImage, 0, 0, null);
imageHashMap.put(relativeFilename, compatibleImage);
return compatibleImage;
}

testEqualsObject

Class: jfreerails.world.common.PositionOnTrackTest

Documentation

No documentation available

Source Code

/*
* Test for boolean equals(Object)
*/
public void testEqualsObject() {
PositionOnTrack p1 = PositionOnTrack.createComingFrom(10, 20,
Step.NORTH);
PositionOnTrack p2 = PositionOnTrack.createComingFrom(10, 20,
Step.NORTH);
assertEquals(p1, p2);
p1 = PositionOnTrack.createComingFrom(10, 50, Step.NORTH);
p2 = PositionOnTrack.createComingFrom(10, 20, Step.NORTH);
assertTrue(!p1.equals(p2));
}

generateMove

Class: jfreerails.server.TrainMaintenanceMoveGenerator

Documentation

No documentation available

Source Code

private static AddTransactionMove generateMove(World w,
FreerailsPrincipal principal) {
NonNullElements trains = new NonNullElements(KEY.TRAINS, w, principal);
int numberOfTrains = trains.size();
long amount = numberOfTrains * 5000;
Transaction t = new Bill(new Money(amount),
Transaction.Category.TRAIN_MAINTENANCE);
return new AddTransactionMove(principal, t);
}

hashCode

Class: jfreerails.move.MapDiff

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = x;
result = 29 * result + y;
result = 29 * result + before.hashCode();
result = 29 * result + after.hashCode();
return result;
}

Called Methods

No outgoing method calls

IncomeStatementHtmlJPanel

Class: jfreerails.client.view.IncomeStatementHtmlJPanel

Documentation

No documentation available

Source Code

public IncomeStatementHtmlJPanel() {
super();
URL url = IncomeStatementHtmlJPanel.class
.getResource("/jfreerails/client/view/income_statement.htm");
template = loadText(url);
}

testTotalShares

Class: jfreerails.controller.FinancialDataGathererTest

Documentation

No documentation available

Source Code

public void testTotalShares() {
FinancialDataGatherer fdg = new FinancialDataGatherer(w, player
.getPrincipal());
int expected = FinancialMoveProducer.IPO_SIZE;
assertEquals(expected, fdg.totalShares());
}

execute

Class: jfreerails.network.specifics.NewGameMessage2Server

Documentation

No documentation available

Source Code

public MessageStatus execute(ServerControlInterface server) {
try {
server.newGame(mapName);
return new MessageStatus(id, true);
} catch (Exception e) {
return new MessageStatus(id, false, e.getMessage());
}
}

toInts

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

public static int[] toInts(PositionOnTrack[] pos) {
int[] returnValue = new int[pos.length];
for (int i = 0; i < pos.length; i++) {
returnValue[i] = pos[i].toInt();
}
return returnValue;
}

TrackMoveProducer

Class: jfreerails.controller.TrackMoveProducer

Documentation

No documentation available

Source Code

public TrackMoveProducer(ModelRoot mr) {
this.executor = mr;
if(null == mr) throw new NullPointerException();
this.mr = mr;
ReadOnlyWorld world = executor.getWorld();
FreerailsPrincipal principal = executor.getPrincipal();
transactionsGenerator = new TrackMoveTransactionsGenerator(world,
principal);
setBuildTrackStrategy(BuildTrackStrategy.getDefault(world));
}

addListDataListener

Class: jfreerails.client.view.World2ListModelAdapter

Documentation

No documentation available

Source Code

public void addListDataListener(ListDataListener arg0) {
// TODO Auto-generated method stub
}

Called Methods

No outgoing method calls

tryUndoMove

Class: jfreerails.move.ChangeItemInListMove

Documentation

No documentation available

Source Code

public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
return tryMove(before, after, w);
}

drawTrackPieceIcon

Class: jfreerails.client.renderer.NullTrackPieceRenderer

Documentation

No documentation available

Source Code

/*
* @see TrackPieceView#drawTrackPieceIcon(int, Graphics, int, int,
* Dimension)
*/
public void drawTrackPieceIcon(int trackTemplate, Graphics g, int x, int y,
Dimension tileSize) {
// Draw nothing since there no track here.
}

Called Methods

No outgoing method calls

setAutoConsist

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void setAutoConsist() {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
newOrders = new TrainOrdersModel(oldOrders.getStationID(), null, false,
true);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}

addD2

Class: jfreerails.util.List2D

Documentation

No documentation available

Source Code

int addD2(int d1, T element);

Called Methods

No outgoing method calls

WagonLoad

Class: jfreerails.controller.WagonLoad

Documentation

No documentation available

Source Code

WagonLoad(int q, int t) {
quantity = q;
cargoType = t;
}

Called Methods

No outgoing method calls

testHit1

Class: jfreerails.client.renderer.TrainRendererTest

Documentation

No documentation available

Source Code

@Test
public void testHit1() {
Point wagonCenter = new Point(100, 100);
Point mouseClick = new Point(100, 100);
boolean hit = isHit(wagonCenter, mouseClick, Step.NORTH);
assertTrue(hit);
}

equals

Class: jfreerails.world.terrain.CityModel

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof CityModel))
return false;
final CityModel cityModel = (CityModel) o;
if (x != cityModel.x)
return false;
if (y != cityModel.y)
return false;
if (!name.equals(cityModel.name))
return false;
return true;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.move.ChangeGameSpeedMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = oldSpeed.hashCode();
result = 29 * result + newSpeed.hashCode();
return result;
}

testSetValuesFromInt

Class: jfreerails.world.common.PositionOnTrackTest

Documentation

No documentation available

Source Code

public void testSetValuesFromInt() {
PositionOnTrack p1 = PositionOnTrack.createComingFrom(10, 20,
Step.NORTH);
int i = p1.toInt();
PositionOnTrack p2 = PositionOnTrack
.createComingFrom(60, 70, Step.EAST);
assertTrue(!p1.equals(p2));
p2.setValuesFromInt(i);
assertEquals(p1, p2);
Step v = Step.getInstance(7); // 7 is the
// maximum
// vector
// number.
p1 = PositionOnTrack.createComingFrom(PositionOnTrack.MAX_COORDINATE,
PositionOnTrack.MAX_COORDINATE, v);
i = p1.toInt();
}

getScale

Class: jfreerails.client.renderer.MapRenderer

Documentation

No documentation available

Source Code

float getScale();

Called Methods

No outgoing method calls

compareTo

Class: jfreerails.world.common.GameTime

Documentation

/**
* Compares two GameTimes for ordering.
*
* @param t
* @return 0 if t is equal to this GameTime; a value less than 0 if this
* GameTime is before t; and a value greater than 0 if this GameTime
* is after t.
*/

Source Code

/**
* Compares two GameTimes for ordering.
*
* @param t
* @return 0 if t is equal to this GameTime; a value less than 0 if this
* GameTime is before t; and a value greater than 0 if this GameTime
* is after t.
*/
public int compareTo(GameTime t) {
return ticks - t.ticks;
}

Called Methods

No outgoing method calls

boundsContain

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public boolean boundsContain(int x, int y) {
if (x >= 0 && x < getMapWidth() && y >= 0 && y < getMapHeight()) {
return true;
}
return false;
}

hashCode

Class: jfreerails.util.List1DImpl

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return size();
}

setUp

Class: jfreerails.util.List3DDiffTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
underlying = new List3DImpl<Object>(0, 0);
map = new TreeMap<ListKey, Object>();
diffs = new List3DDiff<Object>(map, underlying, listid.test);
}

Called Methods

No outgoing method calls

undoMoves

Class: jfreerails.move.CompositeMove

Documentation

No documentation available

Source Code

private void undoMoves(World w, int number, FreerailsPrincipal p) {
for (int i = number; i >= 0; i--) {
MoveStatus ms = moves.get(i).undoMove(w, p);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
}
}

generateFilename

Class: jfreerails.client.renderer.StandardTileRenderer

Documentation

No documentation available

Source Code

public static String generateFilename(String typeName) {
return "terrain" + File.separator + typeName + ".png";
}

Called Methods

No outgoing method calls

jList1MouseClicked

Class: jfreerails.client.view.TrainListJPanel

Documentation

No documentation available

Source Code

private void jList1MouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_jList1MouseClicked
// Add your handling code here:
if (evt.getClickCount() == 2) {
showTrainDetails.actionPerformed(null);
}
}// GEN-LAST:event_jList1MouseClicked

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.top.TestState

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TestState))
return false;
final TestState testState = (TestState) o;
if (x != testState.x)
return false;
return true;
}

Called Methods

No outgoing method calls

getPasswords

Class: jfreerails.server.ServerGameModelImpl

Documentation

No documentation available

Source Code

public String[] getPasswords() {
return passwords.clone();
}

Called Methods

  • _Dummy_.__Array__.clone (external)

propertyChange

Class: jfreerails.client.common.MappedButtonModel

Documentation

No documentation available

Source Code

public void propertyChange(PropertyChangeEvent e) {
setEnabled(((Action) e.getSource()).isEnabled());
}

Called Methods

No outgoing method calls

setX

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

public void setX(int x) {
this.x = x;
}

Called Methods

No outgoing method calls

getWagon

Class: jfreerails.world.train.TrainModel

Documentation

No documentation available

Source Code

public int getWagon(int i) {
return wagonTypes.get(i);
}

addCompleteMoveReceiver

Class: jfreerails.network.specifics.MoveChainFork

Documentation

No documentation available

Source Code

public void addCompleteMoveReceiver(MoveReceiver moveReceiver) {
if (null == moveReceiver) {
throw new NullPointerException();
}
moveReceivers.add(moveReceiver);
}

Called Methods

No outgoing method calls

sizeD1

Class: jfreerails.util.List2DImpl

Documentation

No documentation available

Source Code

public int sizeD1() {
return elementData.size();
}

Called Methods

No outgoing method calls

getArray

Class: jfreerails.util.IntArray

Documentation

/**
* Get the backing array. This method is used by the type-agnostic base
* class code to access the array used for type-specific storage.
*
* @return backing array object
*/

Source Code

/**
* Get the backing array. This method is used by the type-agnostic base
* class code to access the array used for type-specific storage.
*
* @return backing array object
*/
@Override
protected final Object getArray() {
return baseArray;
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.world.common.ImPoint

Documentation

No documentation available

Source Code

@Override
public String toString() {
return "ImPoint{" + x + ", " + y + "}";
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.terrain.Production

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = cargoType;
result = 29 * result + rate;
return result;
}

Called Methods

No outgoing method calls

advanceTimeOneTick

Class: jfreerails.controller.StockPriceCalculatorTest

Documentation

No documentation available

Source Code

private void advanceTimeOneTick() {
int currentTicks = w.currentTime().getTicks();
GameTime newTime = new GameTime(currentTicks + 1);
w.setTime(newTime);
}

getDuration

Class: jfreerails.world.top.ActivityIteratorImpl

Documentation

No documentation available

Source Code

public double getDuration() {
return ant.act.duration();
}

hashCode

Class: jfreerails.world.cargo.ImmutableCargoBundle

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return amounts.size();
}

tryUndoMove

Class: jfreerails.move.ChangeTrackPieceMove

Documentation

No documentation available

Source Code

public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
return tryMove(w, this.trackPieceAfter, this.trackPieceBefore);
}

undoMove

Class: jfreerails.move.ChangeProductionAtEngineShopMove

Documentation

No documentation available

Source Code

public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryUndoMove(w, p);
if (status.isOk()) {
StationModel station = (StationModel) w.get(principal,
KEY.STATIONS, stationNumber);
station = new StationModel(station, this.before);
w.set(principal, KEY.STATIONS, stationNumber, station);
}
return status;
}

set

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public void set(FreerailsPrincipal p, KEY key, int index,
FreerailsSerializable element) {
int playerIndex = p.getWorldIndex();
lists.set(playerIndex, key.getKeyID(), index, element);
}

generateTrackRuleList

Class: jfreerails.world.top.MapFixtureFactory

Documentation

No documentation available

Source Code

public static void generateTrackRuleList(World world) {
TrackRule[] trackRulesArray = new TrackRule[3];
TrackRuleProperties[] trackRuleProperties = new TrackRuleProperties[3];
LegalTrackConfigurations[] legalTrackConfigurations = new LegalTrackConfigurations[3];
LegalTrackPlacement[] legalTrackPlacement = new LegalTrackPlacement[3];
HashSet<TerrainType.Category> cannotBuildOnTheseTerrainTypes = new HashSet<TerrainType.Category>();
cannotBuildOnTheseTerrainTypes.add(TerrainType.Category.Ocean);
// 1st track type..
String[] trackTemplates0 = { "000010000", "010010000", "010010010",
"100111000", "001111000", "010110000", "100110000", "100011000" };
legalTrackConfigurations[0] = new LegalTrackConfigurations(-1,
trackTemplates0);
trackRuleProperties[0] = new TrackRuleProperties(1, false, "type0",
TrackRule.TrackCategories.track, 0, 0, 10, 0);
legalTrackPlacement[0] = new LegalTrackPlacement(
cannotBuildOnTheseTerrainTypes,
LegalTrackPlacement.PlacementRule.ANYWHERE_EXCEPT_ON_THESE);
trackRulesArray[0] = new TrackRuleImpl(trackRuleProperties[0],
legalTrackConfigurations[0], legalTrackPlacement[0]);
// 2nd track type..
String[] trackTemplates1 = { "000010000", "010010000", "010010010" };
legalTrackConfigurations[1] = new LegalTrackConfigurations(-1,
trackTemplates1);
trackRuleProperties[1] = new TrackRuleProperties(2, false, "type1",
TrackRule.TrackCategories.track, 0, 0, 20, 0);
legalTrackPlacement[1] = new LegalTrackPlacement(
cannotBuildOnTheseTerrainTypes,
LegalTrackPlacement.PlacementRule.ANYWHERE_EXCEPT_ON_THESE);
trackRulesArray[1] = new TrackRuleImpl(trackRuleProperties[1],
legalTrackConfigurations[1], legalTrackPlacement[1]);
// 3rd track type..
trackRuleProperties[2] = new TrackRuleProperties(3, false, "type2",
TrackRule.TrackCategories.track, 0, 0, 30, 0);
String[] trackTemplates2 = { "000010000" };
legalTrackConfigurations[2] = new LegalTrackConfigurations(-1,
trackTemplates2);
legalTrackPlacement[2] = new LegalTrackPlacement(
cannotBuildOnTheseTerrainTypes,
LegalTrackPlacement.PlacementRule.ANYWHERE_EXCEPT_ON_THESE);
trackRulesArray[2] = new TrackRuleImpl(trackRuleProperties[2],
legalTrackConfigurations[2], legalTrackPlacement[2]);
// Add track rules to world
for (int i = 0; i < trackRulesArray.length; i++) {
world.add(SKEY.TRACK_RULES, trackRulesArray[i]);
}
// Add the terrain types if necessary.
if (world.size(SKEY.TERRAIN_TYPES) == 0) {
generateTerrainTypesList(world);
}
}

loadGame

Class: jfreerails.network.specifics.SavedGamesManager4UnitTests

Documentation

No documentation available

Source Code

public Serializable loadGame(String name) throws IOException {
Serializable o = savedGames.get(name);
return Utils.cloneBySerialisation(o);
}

tileB

Class: jfreerails.world.track.TrackSection

Documentation

No documentation available

Source Code

public ImPoint tileB(){
return Step.move(tile, step);
}

addPropertyChangeListener

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public void addPropertyChangeListener(PropertyChangeListener l) {
propertyChangeSupport.addPropertyChangeListener(l);
}

Called Methods

No outgoing method calls

add

Class: jfreerails.util.IntArray

Documentation

/**
* Add a value at a specified index in the array.
*
* @param index
* index position at which to insert element
* @param value
* value to be inserted into array
*/

Source Code

/**
* Add a value at a specified index in the array.
*
* @param index
* index position at which to insert element
* @param value
* value to be inserted into array
*/
public void add(int index, int value) {
makeInsertSpace(index);
baseArray[index] = value;
}

refreshTile

Class: jfreerails.client.renderer.ZoomedOutMapRenderer

Documentation

No documentation available

Source Code

public void refreshTile(int x, int y) {
refreshTile(new Point(x, y));
}

SimpleAStarPathFinderTest

Class: jfreerails.controller.SimpleAStarPathFinderTest

Documentation

/**
* Constructor for SimpleAStarPathFinderTest.
*
* @param arg0
*/

Source Code

/**
* Constructor for SimpleAStarPathFinderTest.
*
* @param arg0
*/
public SimpleAStarPathFinderTest(String arg0) {
super(arg0);
}

Called Methods

No outgoing method calls

setupSearch

Class: jfreerails.controller.PathOnTrackFinder

Documentation

No documentation available

Source Code

public void setupSearch(ImPoint from, ImPoint target) throws PathNotFoundException {
startPoint = from;
logger
.fine("Find track path from " + from + " to "
+ target);
/* Check there is track at both the points. */
FreerailsTile tileA = (FreerailsTile) world.getTile(from.x,
from.y);
FreerailsTile tileB = (FreerailsTile) world.getTile(target.x,
target.y);
if (!tileA.hasTrack()) {
throw new PathNotFoundException("No track at " + from.x
+ ", " + from.y + ".");
}
if (!tileB.hasTrack()) {
throw new PathNotFoundException("No track at " + target.x
+ ", " + target.y + ".");
}
PositionOnTrack[] startPoints = FlatTrackExplorer.getPossiblePositions(
world, from);
PositionOnTrack[] targetPoints = FlatTrackExplorer
.getPossiblePositions(world, target);
FlatTrackExplorer explorer = new FlatTrackExplorer(world,
startPoints[0]);
pathFinder.setupSearch(PositionOnTrack.toInts(startPoints),
PositionOnTrack.toInts(targetPoints), explorer);
}

processMove

Class: jfreerails.client.common.Unknown

Documentation

No documentation available

Source Code

public void processMove(Move Move) {
}

Called Methods

No outgoing method calls

getSize

Class: jfreerails.client.view.TrainOrdersListModel

Documentation

No documentation available

Source Code

public int getSize() {
Schedule s = getSchedule();
int size = 0;
if (s != null) {
size = s.getNumOrders();
}
return size;
}

hashCode

Class: jfreerails.world.common.ImSet

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return hashSet.hashCode();
}

Called Methods

No outgoing method calls

parse

Class: jfreerails.server.parser.CargoAndTerrainParser

Documentation

/**
* The recognizer entry method taking a URL.
*
* @param url
* URL source to be parsed.
* @throws java.io.IOException
* on I/O error.
* @throws SAXException
* propagated exception thrown by a DocumentHandler.
* @throws javax.xml.parsers.ParserConfigurationException
* a parser satisfying requested configuration can not be
* created.
*
*/

Source Code

/**
* The recognizer entry method taking a URL.
*
* @param url
* URL source to be parsed.
* @throws java.io.IOException
* on I/O error.
* @throws SAXException
* propagated exception thrown by a DocumentHandler.
* @throws javax.xml.parsers.ParserConfigurationException
* a parser satisfying requested configuration can not be
* created.
*
*/
public static void parse(final java.net.URL url,
final CargoAndTerrainHandler handler) throws SAXException,
javax.xml.parsers.ParserConfigurationException, java.io.IOException {
parse(new InputSource(url.toExternalForm()), handler);
}

subtract

Class: jfreerails.world.track.TrackConfiguration

Documentation

/**
* @return the TrackConfiguration representing the track section c minus the
* track sections represented by v.
*/

Source Code

/**
* @return the TrackConfiguration representing the track section c minus the
* track sections represented by v.
*/
public static TrackConfiguration subtract(FlatTrackTemplate c,
FlatTrackTemplate v) {
/*
* int x=v.getX()+1; int y=v.getY()+1; int oldTemplate
* =c.getTrackGraphicsNumber(); int newTemplate = oldTemplate ^ (1 <<
* (3 * y + x));
*/
int newTemplate = c.get9bitTemplate() & (~v.get9bitTemplate());
return from9bitTemplate(newTemplate);
}

test4Bug1266695

Class: jfreerails.world.train.TrainMotionTest

Documentation

No documentation available

Source Code

public void test4Bug1266695(){
//The figures are copied from the debugger.
ImPoint start = new ImPoint(14, 5);
Step[] vectors= {Step.getInstance(1,1), Step.getInstance(1,0)};
PathOnTiles path = new PathOnTiles(start, vectors);
ConstAcc constAcc0 = ConstAcc.uat(6.5135556243263055d, 0.5d, 6.972888751347389d);
ConstAcc constAcc1 = ConstAcc.uat(10.0, 0.0d, 4.0d);
SpeedAgainstTime speeds = new CompositeSpeedAgainstTime(constAcc0, constAcc1);
double expectedTotalDistance= 97.57359312880715d; //Copied from debugger.
double actualTotalDistance = speeds.getS();
assertEquals(expectedTotalDistance, actualTotalDistance,0d);
double expectedDuration = 10.972888751347389d;
double actualDuration = speeds.getT();
assertEquals(expectedDuration, actualDuration,0d);
int engineStep = 1;
int trainLength = 24;
TrainMotion motion = new TrainMotion(path,engineStep, trainLength, speeds);
double expectedInitialPosition = 42.42640687119285;
double actualInitialPosition = motion.getInitialPosition();
assertEquals(expectedInitialPosition, actualInitialPosition,0d);
//Different from above
double tooLongDuration = 3.9936298481613424d;
actualDuration = motion.duration();
assertTrue(tooLongDuration > actualDuration);
//This method used to throw an exception
@SuppressWarnings("unused") Object o = motion.getState(actualDuration);
}

testDoubleTrackProblem

Class: jfreerails.controller.TrackBuildingTest

Documentation

/**
* There is a bug where if you build a straight section of double track
* going E, then move the cursor to the end and attempt to build more double
* track going SE, the track path finder builds a loop rather than just
* building track going SE
*
*/

Source Code

/**
* There is a bug where if you build a straight section of double track
* going E, then move the cursor to the end and attempt to build more double
* track going SE, the track path finder builds a loop rather than just
* building track going SE
*
*/
public void testDoubleTrackProblem() {
try {
int trackTypeID = stationBuilder.getTrackTypeID("double track");
bts = BuildTrackStrategy.getSingleRuleInstance(trackTypeID, w);
producer.setBuildTrackStrategy(bts);
ImPoint a = new ImPoint(5, 5);
ImPoint b = new ImPoint(6, 5);
ImPoint c = new ImPoint(7, 6);
pathFinder.setupSearch(a, b, bts);
pathFinder.search(-1);
Step[] path = pathFinder.pathAsVectors();
Step[] expectedPath = { EAST };
assertTrue(Arrays.equals(expectedPath, path));
MoveStatus ms = producer.buildTrack(a, path);
assertTrue(ms.ok);
TrackPiece tp = ((FreerailsTile) w.getTile(b.x, b.y)).getTrackPiece();
assertEquals("We just build double track here.", trackTypeID, tp
.getTrackTypeID());
pathFinder.setupSearch(b, c, bts);
pathFinder.search(-1);
path = pathFinder.pathAsVectors();
assertEquals(1, path.length);
expectedPath = new Step[] { SOUTH_EAST };
assertTrue(Arrays.equals(expectedPath, path));
} catch (PathNotFoundException e) {
fail();
}
}

hashCode

Class: jfreerails.world.station.SupplyAtStation

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return supply.hashCode();
}

createDateJLabel

Class: jfreerails.client.top.GUIComponentFactoryTestImpl

Documentation

No documentation available

Source Code

public JLabel createDateJLabel() {
return datejLabel;
}

Called Methods

No outgoing method calls

gen

Class: experimental.GenerateTrainHighlights

Documentation

No documentation available

Source Code

public static void gen(ImageManager imageManager, Color selection, String filename) {
for (Step step : Step.getList()) {
int tileSize = 30;
Image smallImage = imageManager.newBlankImage(tileSize, tileSize);
Graphics2D g2 = (Graphics2D) smallImage.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(3));
double arcRadius = 5;
g2.rotate(step.getDirection(), tileSize/2, tileSize/2);
RoundRectangle2D roundedRectangle = new RoundRectangle2D.Double(7, 3, 16, 26, arcRadius, arcRadius);
g2.setColor(selection);
g2.fill(roundedRectangle);
g2.dispose();
String name = String.format(filename, step.toAbrvString());
imageManager.setImage(name, smallImage);
}
}

issueStock

Class: jfreerails.world.accounts.StockTransaction

Documentation

No documentation available

Source Code

public static StockTransaction issueStock(int playerId, int quantity,
Money pricePerShare) {
// Issue Stock of the Player
long temp = (pricePerShare.getAmount() * quantity);
temp = temp - temp - temp;
Money amount = new Money(temp).changeSign();
return new StockTransaction(Transaction.Category.ISSUE_STOCK, playerId,
quantity, amount);
}

formMouseMoved

Class: jfreerails.client.common.MyGlassPanel

Documentation

No documentation available

Source Code

// GEN-END:initComponents
private void formMouseMoved(java.awt.event.MouseEvent evt) { // GEN-FIRST:event_formMouseMoved
// Add your handling code here:
}

Called Methods

No outgoing method calls

readCityNames

Class: jfreerails.server.InputCityNames

Documentation

No documentation available

Source Code

public static void readCityNames(World w, URL filename) throws SAXException {
InputSource is = new InputSource(filename.toString());
DefaultHandler handler = new CitySAXParser(w);
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(is, handler);
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
}
}

Called Methods

No outgoing method calls

initComponents

Class: experimental.DialogueBoxTester

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
jLabel1 = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
show = new javax.swing.JMenu();
showBrokerScreen = new javax.swing.JMenuItem();
selectEngine = new javax.swing.JMenuItem();
selectWagons = new javax.swing.JMenuItem();
selectTrainOrders = new javax.swing.JMenuItem();
showControls = new javax.swing.JMenuItem();
showTerrainInfo = new javax.swing.JMenuItem();
showStationInfo = new javax.swing.JMenuItem();
showTrainList = new javax.swing.JMenuItem();
showReportBug = new javax.swing.JMenuItem();
throwException = new javax.swing.JMenuItem();
showCargoWaitingAndDemand = new javax.swing.JMenuItem();
showJavaSystemProperties = new javax.swing.JMenuItem();
showNetworthGraph = new javax.swing.JMenuItem();
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/jfreerails/data/south_america.png")));
jLabel1.setText("Press Esc to close dialogue boxes");
jLabel1.setMinimumSize(new java.awt.Dimension(640, 480));
jLabel1.setPreferredSize(new java.awt.Dimension(640, 480));
getContentPane().add(jLabel1, java.awt.BorderLayout.CENTER);
show.setText("Show");
showBrokerScreen.setText("Broker Screen");
showBrokerScreen.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newspaperActionPerformed(evt);
}
});
show.add(showBrokerScreen);
selectEngine.setText("Select Engine");
selectEngine.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectEngineActionPerformed(evt);
}
});
show.add(selectEngine);
selectWagons.setText("Select Wagons");
selectWagons.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectWagonsActionPerformed(evt);
}
});
show.add(selectWagons);
selectTrainOrders.setText("Train Orders");
selectTrainOrders
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectTrainOrdersActionPerformed(evt);
}
});
show.add(selectTrainOrders);
showControls.setText("Show game controls");
showControls.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showControlsActionPerformed(evt);
}
});
show.add(showControls);
showTerrainInfo.setText("Show Terrain Info");
showTerrainInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showTerrainInfoActionPerformed(evt);
}
});
show.add(showTerrainInfo);
showStationInfo.setText("Show Station Info");
showStationInfo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showStationInfoActionPerformed(evt);
}
});
show.add(showStationInfo);
showTrainList.setText("Train List");
showTrainList.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showTrainListActionPerformed(evt);
}
});
show.add(showTrainList);
showCargoWaitingAndDemand.setText("Cargo waiting & demand");
showCargoWaitingAndDemand
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showCargoWaitingAndDemandActionPerformed(evt);
}
});
show.add(showCargoWaitingAndDemand);
showJavaSystemProperties.setText("Java System Properties");
showJavaSystemProperties
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showJavaSystemPropertiesActionPerformed(evt);
}
});
throwException.setText("Throw Exception");
throwException.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
throw new IllegalArgumentException();
}
});
show.add(showJavaSystemProperties);
showNetworthGraph.setText("Show networth graph");
showNetworthGraph
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
showNetworthGraphActionPerformed(evt);
}
});
show.add(showNetworthGraph);
showReportBug.setText("Report Bug");
showReportBug
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showReportBug();
}
});
show.add(showReportBug);
jMenuBar1.add(show);
setJMenuBar(jMenuBar1);
}// GEN-END:initComponents

updateMaxWagonsText

Class: jfreerails.client.view.SelectWagonsJPanel

Documentation

No documentation available

Source Code

private void updateMaxWagonsText() {
if (wagons.size() >= TrainModel.MAX_NUMBER_OF_WAGONS) {
jLabel1.setText("Max train length is "
+ TrainModel.MAX_NUMBER_OF_WAGONS + " wagons");
} else {
jLabel1.setText("");
}
}

Called Methods

No outgoing method calls

receive

Class: jfreerails.network.InetConnection

Documentation

No documentation available

Source Code

FreerailsSerializable receive() throws IOException, ClassNotFoundException {
Object object = objectInputStream.readObject();
return (FreerailsSerializable) object;
}

Called Methods

No outgoing method calls

isDouble

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

public boolean isDouble() {
return properties.isEnableDoubleTrack();
}

getMaintenanceCost

Class: jfreerails.world.track.TrackRuleProperties

Documentation

No documentation available

Source Code

public Money getMaintenanceCost() {
return maintenanceCost;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.train.SpeedTimeAndStatus

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
long temp;
temp = dt != +0.0d ? Double.doubleToLongBits(dt) : 0l;
result = (int) (temp ^ (temp >>> 32));
temp = speed != +0.0d ? Double.doubleToLongBits(speed) : 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
temp = acceleration != +0.0d ? Double.doubleToLongBits(acceleration)
: 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
temp = s != +0.0d ? Double.doubleToLongBits(s) : 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
result = 29 * result + (activity != null ? activity.hashCode() : 0);
return result;
}

Called Methods

No outgoing method calls

testMove2

Class: jfreerails.move.AddPlayerMoveTest

Documentation

No documentation available

Source Code

public void testMove2() {
Player newPlayer = new Player("New Player");
AddPlayerMove move = AddPlayerMove.generateMove(getWorld(), newPlayer);
assertOkButNotRepeatable(move);
}

write

Class: jfreerails.util.CompressedOutputStream

Documentation

No documentation available

Source Code

@Override
public void write(int b) throws IOException {
if (writeIndex >= buffer.length * 0.80000000000000004D) {
flush();
}
buffer[writeIndex++] = (byte) b;
}

ImList

Class: jfreerails.world.common.ImList

Documentation

No documentation available

Source Code

@SuppressWarnings("unchecked")
public ImList(E... items) {
elementData = (E[]) new FreerailsSerializable[items.length];
for (int i = 0; i < items.length; i++) {
elementData[i] = items[i];
}
}

Called Methods

No outgoing method calls

acceleration

Class: jfreerails.controller.MoveTrainPreMove

Documentation

No documentation available

Source Code

double acceleration(int wagons) {
return 0.5d/(wagons + 1);
}

Called Methods

No outgoing method calls

setValuesFromInt

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

public void setValuesFromInt(int i) {
x = i & MAX_COORDINATE;
int shiftedY = i & (MAX_COORDINATE << BITS_FOR_COORDINATE);
y = shiftedY >> BITS_FOR_COORDINATE;
int shiftedDirection = i & (MAX_DIRECTION << (2 * BITS_FOR_COORDINATE));
int directionAsInt = shiftedDirection >> (2 * BITS_FOR_COORDINATE);
cameFrom = Step.getInstance(directionAsInt);
}

toString

Class: jfreerails.world.train.WagonType

Documentation

No documentation available

Source Code

@Override
public String toString() {
return typeName;
}

Called Methods

No outgoing method calls

tryMove

Class: jfreerails.move.ChangeItemInListMove

Documentation

No documentation available

Source Code

protected MoveStatus tryMove(FreerailsSerializable to,
FreerailsSerializable from, World w) {
if (index >= w.size(principal, listKey)) {
return MoveStatus.moveFailed("w.size(listKey) is "
+ w.size(principal, listKey) + " but index is " + index);
}
FreerailsSerializable item2change = w.get(principal, listKey, index);
if (null == item2change) {
if (null == from) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected null but found " + from);
}
if (!from.equals(item2change)) {
String message = "Expected " + from.toString() + " but found "
+ to.toString();
return MoveStatus.moveFailed(message);
}
return MoveStatus.MOVE_OK;
}

equals

Class: jfreerails.move.RemoveItemFromListMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof RemoveItemFromListMove) {
RemoveItemFromListMove test = (RemoveItemFromListMove) o;
if (!this.item.equals(test.getBefore())) {
return false;
}
if (this.index != test.index) {
return false;
}
if (this.listKey != test.listKey) {
return false;
}
return true;
}
return false;
}

setUp

Class: jfreerails.network.AbstractEchoGameServerTestCase

Documentation

No documentation available

Source Code

@Override
protected synchronized void setUp() throws Exception {
echoGameServer = EchoGameServer.startServer();
/*
* There was a problem that occurred intermittently when the unit tests
* were run as a batch. I think it was to do with reusing ports in quick
* succession. Passing 0 as the port allow us to listen on an
* unspecified port whose number we obtain by calling getLocalPort().
* Since making this change, the problem has not occurred.
*/
server = new InetConnectionAccepter(0, echoGameServer);
Thread serverThread = new Thread(server);
serverThread.start();
}

start

Class: experimental.GenerateDependenciesXmlAndHtml

Documentation

No documentation available

Source Code

private void start() {
assert !started;
startXml();
htmlWriter.write("<html>\n");
htmlWriter.write("<title>Dependencies between packages</title>\n");
htmlWriter.write("<p><code>This file was generate by " + sig
+ "</code></p>\n");
htmlWriter.write("<h1>Dependencies between packages</h1>\n");
htmlWriter
.write("<p>The figures below show the dependencies: packages may only depend, i.e. import classes and interfaces, from packages below.</p>\n");
started = true;
}

LeaderBoardJPanel

Class: jfreerails.client.view.LeaderBoardJPanel

Documentation

/**
* This method initializes
*/

Source Code

/**
* This method initializes
*/
public LeaderBoardJPanel() {
super();
values = new Vector<PlayerDetails>();
Random rand = new Random();
for (int i = 0; i < 5; i++) {
PlayerDetails p = new PlayerDetails();
p.networth = new Money(rand.nextInt(100));
values.add(p);
}
initialize();
}

testAddToTail

Class: jfreerails.world.train.TrainPositionOnMapTest

Documentation

No documentation available

Source Code

public void testAddToTail() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
TrainPositionOnMap d;
TrainPositionOnMap f;
TrainPositionOnMap g;
TrainPositionOnMap i;
TrainPositionOnMap j;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
b = TrainPositionOnMap.createInstance(new int[] { 20, 30 }, new int[] {
22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 10, 30 }, new int[] {
11, 33 });
d = a.addToTail(b);
assertEquals(d, c);
f = TrainPositionOnMap.createInstance(new int[] { 40, 50 }, new int[] {
44, 55 });
g = TrainPositionOnMap.createInstance(new int[] { 10, 30, 40 },
new int[] { 11, 33, 44 });
i = TrainPositionOnMap.createInstance(new int[] { 10, 30, 50 },
new int[] { 11, 33, 55 });
j = g.addToTail(f);
assertEquals(i, j);
}

reset

Class: jfreerails.client.renderer.BuildTrackController

Documentation

/** Cancels any proposed track and resets the path finder. */

Source Code

/** Cancels any proposed track and resets the path finder. */
private void reset() {
worldDiffs.reset();
path4newTrackFinder.abandonSearch();
this.builtTrack.clear();
this.isBuildTrackSuccessful = false;
}

NetWorthCalculator

Class: jfreerails.controller.NetWorthCalculator

Documentation

No documentation available

Source Code

public NetWorthCalculator(ReadOnlyWorld w, FreerailsPrincipal principal) {
super(w, principal);
}

setup

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

No documentation available

Source Code

public void setup(ModelRoot mr, ActionRoot ar, RenderersRoot vl,
ActionListener al) {
modelRoot = mr;
stationBuildModel = ar.getStationBuildModel();
trackMoveProducer = ar.getTrackMoveProducer();
if (null == trackMoveProducer)
throw new NullPointerException();
selectionSet = new HashMap<TrackRule.TrackCategories, Integer>();
trackButtonGroup = new javax.swing.ButtonGroup();
bridgeButtonGroup = new javax.swing.ButtonGroup();
stationButtonGroup = new javax.swing.ButtonGroup();
tunnelButtonGroup = new javax.swing.ButtonGroup();
// Remove any existing buttons.
bridgesJPanel.removeAll();
stationsJPanel.removeAll();
trackJPanel.removeAll();
tunnelsJPanel.removeAll();
// Add the new set of buttons.
ReadOnlyWorld world = mr.getWorld();
for (int i = 0; i < world.size(SKEY.TRACK_RULES); i++) {
JToggleButton toggleButton = new JToggleButton();
final Integer ruleID = new Integer(i);
TrackRule rule = (TrackRule) world.get(SKEY.TRACK_RULES, i);
TrackRule.TrackCategories category = rule.getCategory();
Money price = null;
switch (category) {
case track:
trackButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon(rule.getTypeName()));
toggleButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
selectionSet
.put(TrackRule.TrackCategories.track,
ruleID);
setBuildTrackStrategy();
}
});
price = rule.getPrice();
trackJPanel.add(toggleButton);
break;
case bridge:
bridgeButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon(rule.getTypeName()));
toggleButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
selectionSet.put(
TrackRule.TrackCategories.bridge,
ruleID);
setBuildTrackStrategy();
}
});
bridgesJPanel.add(toggleButton);
price = rule.getFixedCost();
break;
case tunnel:
tunnelButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon(rule.getTypeName()));
toggleButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
selectionSet.put(
TrackRule.TrackCategories.tunnel,
ruleID);
setBuildTrackStrategy();
}
});
price = rule.getPrice();
tunnelsJPanel.add(toggleButton);
break;
case station:
stationButtonGroup.add(toggleButton);
toggleButton.setAction(stationBuildModel
.getStationChooseAction(ruleID));
toggleButton.setIcon(getIcon(rule.getTypeName()));
toggleButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
selectionSet.put(
TrackRule.TrackCategories.station,
ruleID);
}
});
stationsJPanel.add(toggleButton);
price = rule.getFixedCost();
break;
}
toggleButton.setPreferredSize(new java.awt.Dimension(36, 36));
String tooltip = Utils.capitalizeEveryWord(rule.getTypeName())
+ " $" + price.toString();
toggleButton.setToolTipText(tooltip);
if (!selectionSet.containsKey(category)) {
selectionSet.put(category, new Integer(i));
toggleButton.setSelected(true);
}
}
addNoTunnelsButton();
addNoBridgesButton();
// Default to add track.
addTrackActionPerformed(null);
buildModeButtonGroup.setSelected(addTrack.getModel(), true);
setBuildTrackStrategy();
// Make the buttons non-focusable
setFocusableFalse(bridgeButtonGroup);
setFocusableFalse(trackButtonGroup);
setFocusableFalse(tunnelButtonGroup);
setFocusableFalse(stationButtonGroup);
setFocusableFalse(buildModeButtonGroup);
// Add button click
// buildTrackJPanel.addKeyListener(new KeyListener(){
// public void keyPressed(KeyEvent e){
// System.out.println(e.getKeyCode());
// viewMode.doClick();
// }
// public void keyReleased(KeyEvent e){
//
// }
// public void keyTyped(KeyEvent e){
//
// }
// });
}

removeMapListener

Class: jfreerails.network.specifics.MoveChainFork

Documentation

No documentation available

Source Code

public void removeMapListener(WorldMapListener l) {
mapListeners.remove(l);
}

Called Methods

No outgoing method calls

showTrainOrders

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showTrainOrders(int trainId) {
closeContent();
if (trainId != -1) {
trainDialogueJPanel.display(trainId);
showContent(trainDialogueJPanel);
}
}

getTrackRule

Class: jfreerails.world.track.TrackPiece

Documentation

No documentation available

Source Code

TrackRule getTrackRule();

Called Methods

No outgoing method calls

TrainSummaryJPanel

Class: jfreerails.client.view.TrainSummaryJPanel

Documentation

/** Creates new form TrainSummaryJPanel */

Source Code

/** Creates new form TrainSummaryJPanel */
public TrainSummaryJPanel() {
initComponents();
}

addD2

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

public int addD2(int d1) {
return super.addDimension(d1);
}

getMapHeight

Class: jfreerails.world.top.WorldDiffs

Documentation

No documentation available

Source Code

@Override
public int getMapHeight() {
return underlying.getMapHeight();
}

generateMove

Class: jfreerails.controller.TimeTickPreMove

Documentation

No documentation available

Source Code

public Move generateMove(ReadOnlyWorld w) {
return TimeTickMove.getMove(w);
}

testGetStepIndex

Class: jfreerails.world.train.PathOnTilesTest

Documentation

No documentation available

Source Code

public void testGetStepIndex() {
ImPoint start = new ImPoint();
Step[] vectors = new Step[] { SOUTH_EAST, EAST, EAST };
PathOnTiles path = new PathOnTiles(start, vectors);
assertEquals(0, path.getStepIndex(0));
assertEquals(0, path.getStepIndex(1));
assertEquals(0, path.getStepIndex(30));
assertEquals(1, path.getStepIndex(60));
assertEquals(2, path.getStepIndex(90));
}

write

Class: jfreerails.network.specifics.SimpleServerGameModel

Documentation

No documentation available

Source Code

public void write(ObjectOutputStream objectOut) throws IOException {
}

Called Methods

No outgoing method calls

StationModel

Class: jfreerails.world.station.StationModel

Documentation

No documentation available

Source Code

public StationModel(int x, int y, String stationName,
int numberOfCargoTypes, int cargoBundle) {
this.name = stationName;
this.x = x;
this.y = y;
production = new ImList<PlannedTrain>();
supply = new SupplyAtStation(new int[numberOfCargoTypes]);
demand = new Demand4Cargo(new boolean[numberOfCargoTypes]);
converted = ConvertedAtStation.emptyInstance(numberOfCargoTypes);
cargoBundleNumber = cargoBundle;
}

findPath2Target

Class: jfreerails.controller.MoveTrainPreMove3rdTest

Documentation

No documentation available

Source Code

private void findPath2Target(ImPoint target1, Step[] expectedPath) {
FreerailsTile tile = (FreerailsTile)world.getTile(target1.x, target1.y);
assertTrue(tile.hasTrack());
PositionOnTrack pot = PositionOnTrack.createFacing(10, 10, EAST);
for (int i = 0; i < expectedPath.length; i++) {
Step expected = expectedPath[i];
Step actual = MoveTrainPreMove.findNextStep(world,pot, target1);
assertEquals(String.valueOf(i), expected, actual);
pot.move(expected);
}
}

getTrackTypeID

Class: jfreerails.controller.StationBuilder

Documentation

No documentation available

Source Code

public int getTrackTypeID(String string) {
ReadOnlyWorld w = executor.getWorld();
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule r = (TrackRule) w.get(SKEY.TRACK_RULES, i);
if (string.equals(r.getTypeName())) {
return i;
}
}
throw new NoSuchElementException();
}

noDiagonalTrackConflicts

Class: jfreerails.move.ChangeTrackPieceMove

Documentation

No documentation available

Source Code

private boolean noDiagonalTrackConflicts(ImPoint point, int trackTemplate,
World w) {
/*
* This method is needs replacing. It only deals with flat track pieces,
* and is rather hard to make sense of. LL
*/
// int trackTemplate = (1 << (3 * (1 + tv.getY()) + (1 + tv.getX())));
int trackTemplateAbove;
int trackTemplateBelow;
int cornersTemplate = TrackConfiguration
.stringTemplate2Int("101000101");
trackTemplate = trackTemplate & cornersTemplate;
Dimension mapSize = new Dimension(w.getMapWidth(), w.getMapHeight());
// Avoid array-out-of-bounds exceptions.
if (point.y > 0) {
FreerailsTile ft = (FreerailsTile)w.getTile(point.x, point.y - 1);
TrackPiece tp = ft.getTrackPiece();
trackTemplateAbove = tp.getTrackGraphicID();
} else {
trackTemplateAbove = 0;
}
if ((point.y + 1) < mapSize.height) {
FreerailsTile ft = (FreerailsTile)w.getTile(point.x, point.y + 1);
TrackPiece tp = ft.getTrackPiece();
trackTemplateBelow = tp.getTrackGraphicID();
} else {
trackTemplateBelow = 0;
}
trackTemplateAbove = trackTemplateAbove >> 6;
trackTemplateBelow = trackTemplateBelow << 6;
trackTemplate = trackTemplate
& (trackTemplateAbove | trackTemplateBelow);
if (trackTemplate != 0) {
return false;
// There is a clash.
}
return true;
// Things are ok.
}

connect

Class: jfreerails.network.specifics.FreerailsClient

Documentation

/**
* Connects this client to a remote server.
*/

Source Code

/**
* Connects this client to a remote server.
*/
public final LogOnResponse connect(String address, int port,
String username, String password) {
logger.fine("Connect to remote server. " + address + ":" + port);
try {
connection2Server = new InetConnection2Server(address, port);
} catch (IOException e) {
return LogOnResponse.rejected(e.getMessage());
}
try {
LogOnRequest request = new LogOnRequest(username, password);
connection2Server.writeToServer(request);
connection2Server.flush();
LogOnResponse response = (LogOnResponse) connection2Server
.waitForObjectFromServer();
return response;
} catch (Exception e) {
try {
connection2Server.disconnect();
} catch (IOException e1) {
e1.printStackTrace();
}
return LogOnResponse.rejected(e.getMessage());
}
}

ensureCapacity

Class: jfreerails.util.GrowableBase

Documentation

/**
* Ensure that the array has the capacity for at least the specified number
* of values.
*
* @param min
* minimum capacity to be guaranteed
*/

Source Code

/**
* Ensure that the array has the capacity for at least the specified number
* of values.
*
* @param min
* minimum capacity to be guaranteed
*/
public final void ensureCapacity(int min) {
if (min > countLimit) {
growArray(min);
}
}

writeTile

Class: jfreerails.server.CityEconomicModel

Documentation

No documentation available

Source Code

private void writeTile(World w, Tile tile) {
int type = 0;
while (!w.get(SKEY.TERRAIN_TYPES, type).equals(tile.type)) {
type++;
}
int x = tile.p.x;
int y = tile.p.y;
FreerailsTile fTile = (FreerailsTile) w.getTile(x, y);
fTile = FreerailsTile.getInstance(type, fTile.getTrackPiece());
w.setTile(x, y, fTile);
}

getCategory

Class: jfreerails.world.terrain.NullTerrainType

Documentation

No documentation available

Source Code

public Category getCategory() {
return Category.Country;
}

Called Methods

No outgoing method calls

newMap

Class: jfreerails.server.SavedGamesManagerImpl

Documentation

No documentation available

Source Code

public Serializable newMap(String name) throws IOException {
return OldWorldImpl.createWorldFromMapFile(name,
FreerailsProgressMonitor.NULL_INSTANCE);
}

hashCode

Class: jfreerails.util.List2DDiff

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return sizeD1();
}

newMap

Class: jfreerails.network.specifics.SavedGamesManager

Documentation

No documentation available

Source Code

Serializable newMap(String name) throws IOException;

Called Methods

No outgoing method calls

getOwnerID

Class: jfreerails.world.track.TrackPieceImpl

Documentation

No documentation available

Source Code

public int getOwnerID() {
return ownerID;
}

Called Methods

No outgoing method calls

testInvalidSchedule

Class: jfreerails.controller.AddTrainPreMoveTest

Documentation

No documentation available

Source Code

public void testInvalidSchedule() {
try {
TrainOrdersModel order0 = new TrainOrdersModel(10, null, false, false);
TrainOrdersModel order1 = new TrainOrdersModel(1, null, false, false);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
ImmutableSchedule invalidSchedule = s.toImmutableSchedule();
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0),
stationA, principal, invalidSchedule);
preMove.generateMove(world);
fail();
} catch (ArrayIndexOutOfBoundsException e) {
}
}

setMoveReceiver

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public void setMoveReceiver(UntriedMoveReceiver moveReceiver) {
this.moveReceiver = moveReceiver;
}

Called Methods

No outgoing method calls

getStationID

Class: jfreerails.controller.TrainStopsHandler

Documentation

/**
* @return the number of the station the train is currently at, or -1 if no
* current station.
*/

Source Code

/**
* @return the number of the station the train is currently at, or -1 if no
* current station.
*/
public int getStationID(int x, int y) {
// loop thru the station list to check if train is at the same Point
// as
// a station
for (int i = 0; i < worldDiffs.size(principal, KEY.STATIONS); i++) {
StationModel tempPoint = (StationModel) worldDiffs.get(principal, KEY.STATIONS, i);
if (null != tempPoint && (x == tempPoint.x) && (y == tempPoint.y)) {
return i; // train is at the station at location tempPoint
}
}
return -1;
// there are no stations that exist where the train is currently
}

testContract

Class: jfreerails.world.train.ConstAccTest

Documentation

No documentation available

Source Code

public void testContract(){
Random r = new Random(88);
for(int i = 0; i < 1000; i++){
ConstAcc acc1 = ConstAcc.uat(r.nextDouble(), r.nextDouble(), r.nextDouble());
checkContract(acc1);
ConstAcc acc2 = ConstAcc.uas(r.nextDouble(), r.nextDouble(), r.nextDouble());
checkContract(acc2);
}
}

getTiles

Class: jfreerails.world.train.TrainMotion

Documentation

/**
* Returns a PathOnTiles object that identifies the tiles the train is on at
* the specified time.
*
* @param t
* the time.
* @return an array of the tiles the train is on
* @throws IllegalArgumentException
* if t is outside the interval
*/

Source Code

/**
* Returns a PathOnTiles object that identifies the tiles the train is on at
* the specified time.
*
* @param t
* the time.
* @return an array of the tiles the train is on
* @throws IllegalArgumentException
* if t is outside the interval
*/
public PathOnTiles getTiles(double t) {
checkT(t);
t = Math.min(t, speeds.getT());
double start = calcOffSet(t);
double end = start + trainLength;
ArrayList<Step> steps = new ArrayList<Step>();
double distanceSoFar = 0;
int stepsBeforeStart = 0;
int stepsAfterEnd = 0;
for (int i = 0; i < path.steps(); i++) {
if (distanceSoFar > end)
stepsAfterEnd++;
Step step = path.getStep(i);
distanceSoFar += step.getLength();
if (distanceSoFar < start)
stepsBeforeStart++;
}
if (distanceSoFar < start) {
// throw new IllegalStateException();
}
if (distanceSoFar < (end - 0.1)) {
// throw new IllegalStateException();
}
int lastStep = path.steps() - stepsAfterEnd;
for (int i = stepsBeforeStart; i < lastStep; i++) {
steps.add(path.getStep(i));
}
ImPoint p = path.getStart();
int x = p.x;
int y = p.y;
for (int i = 0; i < stepsBeforeStart; i++) {
Step step = path.getStep(i);
x += step.deltaX;
y += step.deltaY;
}
ImPoint startPoint = new ImPoint(x, y);
PathOnTiles pathOnTiles = new PathOnTiles(startPoint, steps);
return pathOnTiles;
}

hashCode

Class: jfreerails.world.common.Money

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return (int) (amount ^ (amount >>> 32));
}

Called Methods

No outgoing method calls

getScaledImage

Class: jfreerails.client.top.RenderersRootImpl

Documentation

No documentation available

Source Code

public Image getScaledImage(String relativeFilename, int height) throws IOException {
return imageManager.getScaledImage(relativeFilename, height);
}

react2cursorMove

Class: jfreerails.client.view.MapViewJComponentConcrete

Documentation

No documentation available

Source Code

private void react2cursorMove(ImPoint newPoint, ImPoint oldPoint) {
float scale = getMapView().getScale();
Dimension tileSize = new Dimension((int) scale, (int) scale);
Rectangle vr = this.getVisibleRect();
Rectangle rectangleSurroundingCursor = new Rectangle(0, 0, 1, 1);
rectangleSurroundingCursor.setLocation((newPoint.x - 1)
* tileSize.width, (newPoint.y - 1) * tileSize.height);
rectangleSurroundingCursor.setSize(tileSize.width * 3,
tileSize.height * 3);
if (!(vr.contains(rectangleSurroundingCursor))) {
int x = newPoint.x * tileSize.width - vr.width / 2;
int y = newPoint.y * tileSize.height - vr.height / 2;
this.scrollRectToVisible(new Rectangle(x, y, vr.width, vr.height));
}
this.repaint((newPoint.x - 1) * tileSize.width, (newPoint.y - 1)
* tileSize.height, tileSize.width * 3, tileSize.height * 3);
this.repaint((oldPoint.x - 1) * tileSize.width, (oldPoint.y - 1)
* tileSize.height, tileSize.width * 3, tileSize.height * 3);
}

paint

Class: jfreerails.client.renderer.StationBoxRenderer

Documentation

No documentation available

Source Code

public void paint(Graphics2D g) {
Boolean showCargoWaiting = (Boolean) modelRoot
.getProperty(ModelRoot.Property.SHOW_CARGO_AT_STATIONS);
if (showCargoWaiting.booleanValue()) {
/* We only show the station boxes for the current player. */
FreerailsPrincipal principal = modelRoot.getPrincipal();
WorldIterator wi = new NonNullElements(KEY.STATIONS, w, principal);
while (wi.next()) { // loop over non null stations
StationModel station = (StationModel) wi.getElement();
int positionX = (station.getStationX() * Constants.TILE_SIZE)
+ Constants.TILE_SIZE / 2;
int positionY = (station.getStationY() * Constants.TILE_SIZE)
+ Constants.TILE_SIZE * 2;
Rectangle r = new Rectangle(positionX, positionY, MAX_WIDTH,
MAX_HEIGHT);
g.setColor(bgColor);
g.fillRect(positionX, positionY, MAX_WIDTH, MAX_HEIGHT);
g.setColor(Color.WHITE);
g.setStroke(new BasicStroke(1f));
g.drawRect(positionX, positionY, MAX_WIDTH, MAX_HEIGHT);
ImmutableCargoBundle cb = (ImmutableCargoBundle) w.get(
principal, KEY.CARGO_BUNDLES, station
.getCargoBundleID());
int[][] carsLoads = calculateCarLoads(cb);
for (int category = 0; category < CargoType
.getNumberOfCategories(); category++) {
int alternateWidth = (MAX_WIDTH - 2 * SPACING)
/ (carsLoads[category].length + 1);
int xOffsetPerWagon = Math.min(wagonImageWidth,
alternateWidth);
for (int car = 0; car < carsLoads[category].length; car++) {
int x = positionX + (car * xOffsetPerWagon)
+ SPACING;
int y = positionY
+ (category * (WAGON_IMAGE_HEIGHT + SPACING));
int cargoType = carsLoads[category][car];
g.drawImage(cargoImages[cargoType], x, y, null);
}
}
}
}
}

isWaiting4FullLoad

Class: jfreerails.controller.TrainStopsHandler

Documentation

No documentation available

Source Code

public boolean isWaiting4FullLoad() {
TrainModel train = (TrainModel) worldDiffs.get(principal, KEY.TRAINS, this.trainId);
int scheduleID = train.getScheduleID();
ImmutableSchedule schedule = (ImmutableSchedule) worldDiffs.get(principal,
KEY.TRAIN_SCHEDULES, scheduleID);
if(schedule.getNumOrders() == 0){
return false;
}
TrainOrdersModel order = schedule.getOrder(schedule.getOrderToGoto());
return !isTrainFull() && order.waitUntilFull;
}

testBuildTrack

Class: jfreerails.client.renderer.BuildTrackControllerTest

Documentation

No documentation available

Source Code

public void testBuildTrack() {
ImPoint from = new ImPoint(10, 10);
modelRoot.setProperty(Property.CURSOR_POSITION, from);
ImPoint to = new ImPoint(20, 10);
buildTrackController.setProposedTrack(to, trackBuilder);
buildTrackController.updateUntilComplete();
assertTrue(buildTrackController.isBuildTrackSuccessful());
// See if any track has actually been built.
FreerailsTile tile = (FreerailsTile) w.getTile(10, 10);
assertFalse(tile.hasTrack());
buildTrackController.updateWorld(trackBuilder);
tile = (FreerailsTile) w.getTile(10, 10);
assertTrue(tile.hasTrack());
tile = (FreerailsTile) w.getTile(20, 10);
assertTrue(tile.hasTrack());
}

GUIComponentFactoryTestImpl

Class: jfreerails.client.top.GUIComponentFactoryTestImpl

Documentation

/** Creates a new instance of GUIComponentFactoryTestImpl. */

Source Code

/** Creates a new instance of GUIComponentFactoryTestImpl. */
public GUIComponentFactoryTestImpl() {
JPanel mainmapjPanel;
trainsJPanel = new JTabbedPane();
datejLabel = new JLabel();
mapOverview = new JPanel();
cashjLabel = new JLabel();
mainMapView = new JScrollPane();
mainmapjPanel = new JPanel();
messageJLabel = new JLabel();
gameMenu = new JMenu();
buildMenu = new JMenu();
displayMenu = new JMenu();
helpMenu = new JMenu();
brokerMenu = new JMenu();
trainsJPanel.setBackground(new java.awt.Color(255, 51, 51));
datejLabel.setText("Jun, 1840");
mapOverview.setBackground(new java.awt.Color(0, 204, 255));
mapOverview.setPreferredSize(new java.awt.Dimension(100, 100));
cashjLabel.setText("$100,000");
mainmapjPanel.setBackground(new java.awt.Color(153, 244, 51));
mainMapView.setViewportView(mainmapjPanel);
messageJLabel.setText("message");
}

Called Methods

No outgoing method calls

testMove

Class: jfreerails.move.AddActiveEntityMoveTest

Documentation

No documentation available

Source Code

@Override
public void testMove() {
FreerailsPrincipal p = getPrincipal();
Activity a = new WorldImplTest.TestActivity(50);
AddActiveEntityMove move = new AddActiveEntityMove(a, 0,
p);
assertSurvivesSerialisation(move);
assertOkButNotRepeatable(move);
AddActiveEntityMove move2 = new AddActiveEntityMove(a, 2,
p);
assertTryMoveFails(move2);
}

display

Class: jfreerails.client.view.TrainDialogueJPanel

Documentation

No documentation available

Source Code

public void display(int trainNumber) {
wi = new NonNullElements(KEY.TRAINS, w, principal);
wi.gotoIndex(trainNumber);
if (wi.getRowID() > 0) {
this.previousJButton.setEnabled(true);
} else {
this.previousJButton.setEnabled(false);
}
if (wi.getRowID() < (wi.size() - 1)) {
this.nextJButton.setEnabled(true);
} else {
this.nextJButton.setEnabled(false);
}
newTrainScheduleJPanel1.display(trainNumber);
trainDetailsJPanel1.displayTrain(trainNumber);
}

tryDoMove

Class: jfreerails.move.AddItemToSharedListMove

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.size(listKey) != index) {
return MoveStatus.moveFailed("Expected size of "
+ listKey.toString() + " list is " + index
+ " but actual size is " + w.size(listKey));
}
return MoveStatus.MOVE_OK;
}

getProperty

Class: jfreerails.launcher.Launcher

Documentation

No documentation available

Source Code

public String getProperty(String key){
return props.getProperty(key);
}

Called Methods

No outgoing method calls

setNextEnabled

Class: jfreerails.launcher.LauncherInterface

Documentation

No documentation available

Source Code

void setNextEnabled(boolean enabled);

Called Methods

No outgoing method calls

getActivity

Class: jfreerails.world.train.TrainMotion

Documentation

No documentation available

Source Code

public SpeedTimeAndStatus.TrainActivity getActivity() {
return activity;
}

Called Methods

No outgoing method calls

StationModel

Class: jfreerails.world.station.StationModel

Documentation

No documentation available

Source Code

public StationModel(StationModel s, ImList<PlannedTrain> production) {
this.production = production;
this.demand = s.demand;
this.cargoBundleNumber = s.cargoBundleNumber;
this.converted = s.converted;
this.name = s.name;
this.supply = s.supply;
this.x = s.x;
this.y = s.y;
}

Called Methods

No outgoing method calls

getBts

Class: jfreerails.client.top.UserInputOnMapController

Documentation

No documentation available

Source Code

private BuildTrackStrategy getBts() {
BuildTrackStrategy bts = (BuildTrackStrategy) modelRoot
.getProperty(ModelRoot.Property.BUILD_TRACK_STRATEGY);
if (null == bts) {
throw new NullPointerException();
}
return bts;
}

hashCode

Class: jfreerails.world.terrain.Consumption

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = cargoType;
result = 29 * result + prerequisite;
return result;
}

Called Methods

No outgoing method calls

testCreateInstanceFreerailsPathIterator

Class: jfreerails.world.train.TrainPositionOnMapTest

Documentation

No documentation available

Source Code

/*
* Test for TrainPosition createInstance(FreerailsPathIterator)
*/
public void testCreateInstanceFreerailsPathIterator() {
FreerailsPathIterator path = new SimplePathIteratorImpl(new int[] { 40,
30, 20, 10 }, new int[] { 44, 33, 22, 11 });
TrainPositionOnMap a = TrainPositionOnMap
.createInSameDirectionAsPath(path);
assertEquals(a.getLength(), 4);
assertEquals(a.getX(0), 40);
assertEquals(a.getY(0), 44);
assertEquals(a.getX(1), 30);
assertEquals(a.getY(1), 33);
assertEquals(a.getX(2), 20);
assertEquals(a.getY(2), 22);
assertEquals(a.getX(3), 10);
assertEquals(a.getY(3), 11);
}

nextStationActionPerformed

Class: jfreerails.client.view.StationInfoJPanel

Documentation

No documentation available

Source Code

private void nextStationActionPerformed(java.awt.event.ActionEvent evt) {
// GEN-FIRST:event_nextStationActionPerformed
// Add your handling code here:
if (wi.next()) {
ImPoint p = new ImPoint(((StationModel) wi.getElement())
.getStationX(), ((StationModel) wi.getElement())
.getStationY());
this.modelRoot.setProperty(ModelRoot.Property.CURSOR_POSITION, p);
display();
} else {
throw new IllegalStateException();
}
} // GEN-LAST:event_nextStationActionPerformed

getXPoints

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public ImInts getXPoints() {
return xpoints;
}

Called Methods

No outgoing method calls

getCargoBundle

Class: jfreerails.controller.TrainAccessor

Documentation

No documentation available

Source Code

public ImmutableCargoBundle getCargoBundle() {
TrainModel train = getTrain();
return (ImmutableCargoBundle) w.get(p, KEY.CARGO_BUNDLES, train
.getCargoBundleID());
}

getWagonsToAdd

Class: jfreerails.world.train.Schedule

Documentation

/** Returns the wagons to add at the next scheduled stop. */

Source Code

/** Returns the wagons to add at the next scheduled stop. */
ImInts getWagonsToAdd();

Called Methods

No outgoing method calls

isPositionFollowsMouse

Class: jfreerails.client.view.StationBuildModel

Documentation

No documentation available

Source Code

public boolean isPositionFollowsMouse() {
return positionFollowsMouse;
}

Called Methods

No outgoing method calls

disconnect

Class: jfreerails.network.specifics.FreerailsClient

Documentation

/**
* Disconnect the client from the server.
*/

Source Code

/**
* Disconnect the client from the server.
*/
public final void disconnect() {
try {
connection2Server.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}

hasAnyTrackBeenBuilt

Class: jfreerails.move.ChangeTrackPieceCompositeMove

Documentation

/** Returns true if some track has been built. */

Source Code

/** Returns true if some track has been built. */
static boolean hasAnyTrackBeenBuilt(ReadOnlyWorld world,
FreerailsPrincipal principal) {
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
world, principal);
aggregator.setCategory(Transaction.Category.TRACK);
return aggregator.calculateQuantity() > 0;
}

TrainModel

Class: jfreerails.world.train.TrainModel

Documentation

No documentation available

Source Code

public TrainModel(int engine) {
engineTypeId = engine;
wagonTypes = new ImInts(0, 1, 2);
scheduleId = 0;
cargoBundleId = 0;
}

Called Methods

No outgoing method calls

CashJLabel

Class: jfreerails.client.view.CashJLabel

Documentation

No documentation available

Source Code

public CashJLabel() {
this.setText(" ");
}

Called Methods

No outgoing method calls

getSaveGameName

Class: jfreerails.launcher.SelectMapJPanel

Documentation

No documentation available

Source Code

public String getSaveGameName() {
return (String) savedmapsJList.getSelectedValue();
}

Called Methods

No outgoing method calls

FlowRateOutputStream

Class: jfreerails.util.FlowRateOutputStream

Documentation

No documentation available

Source Code

public FlowRateOutputStream(OutputStream out, String streamName) {
this(out, streamName, 60, 1000);
}

close

Class: jfreerails.network.SynchronizedFlag

Documentation

No documentation available

Source Code

public synchronized void close() {
this.isOpen = false;
notifyAll();
}

Called Methods

No outgoing method calls

formComponentShown

Class: jfreerails.launcher.ClientOptionsJPanel

Documentation

No documentation available

Source Code

private void formComponentShown(java.awt.event.ComponentEvent evt) {// GEN-FIRST:event_formComponentShown
validateInput();
}// GEN-LAST:event_formComponentShown

upgradeTrack

Class: jfreerails.controller.TrackMoveProducer

Documentation

No documentation available

Source Code

public MoveStatus upgradeTrack(ImPoint point) {
if (getBuildMode() == BuildMode.UPGRADE_TRACK) {
ReadOnlyWorld w = executor.getWorld();
FreerailsTile tile = (FreerailsTile) w.getTile(point.x, point.y);
int tt = tile.getTerrainTypeID();
return upgradeTrack(point, getBuildTrackStrategy().getRule(tt));
}
throw new IllegalStateException(
"Track builder not set to upgrade track!");
}

ActionRoot

Class: jfreerails.client.view.ActionRoot

Documentation

No documentation available

Source Code

public ActionRoot(ModelRootImpl mr) {
this.serverControls = new ServerControlModel(mr);
}

Called Methods

No outgoing method calls

getBuildTrainDialogAction

Class: jfreerails.client.view.ActionRoot

Documentation

No documentation available

Source Code

public Action getBuildTrainDialogAction() {
return buildTrainDialogAction;
}

Called Methods

No outgoing method calls

startXml

Class: experimental.GenerateDependenciesXmlAndHtml

Documentation

No documentation available

Source Code

private void startXml() {
// Start the file.
xmlWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
xmlWriter
.write("<project basedir=\".\" default=\"checkdep\" name=\"checkdep\">\n");
xmlWriter.write("\t<description>This ant script was generated by "
+ sig
+ " to check the dependencies for jfreerails.</description>\n");
// Set the properties.
// Add the compile target.
xmlWriter
.write("\n\t<target description=\"Build everything except JUnit test-classes\" name=\"compile\">\n");
xmlWriter.write("\t\t<mkdir dir=\"build\" />\n");
xmlWriter
.write("\t\t<javac destdir=\"build\" fork=\"true\" srcdir=\"src\" source=\"1.5\">\n");
xmlWriter.write("\t\t\t<exclude name=\"**/*Test.java\" />\n");
xmlWriter.write("\t\t </javac>\n");
xmlWriter.write("\t</target>\n");
// Start the check depend target.
xmlWriter
.write("\n\n\t<target depends=\"compile\" description=\"Tests whether dependencies between packages conform to the rules defined in this target\" name=\"checkdep\">\n");
}

Called Methods

No outgoing method calls

findpath

Class: jfreerails.controller.SimpleAStarPathFinder

Documentation

No documentation available

Source Code

public IntArray findpath(int[] currentPosition, int[] targets,
GraphExplorer e) throws PathNotFoundException {
logger.fine(currentPosition.length + " starting points; "
+ targets.length + " targets.");
setupSearch(currentPosition, targets, e);
search(-1);
return path;
}

DialogueBoxController

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public DialogueBoxController(JFrame frame, ModelRootImpl mr) {
this.frame = frame;
modelRoot = mr;
// Setup glass panel..
glassPanel = new MyGlassPanel();
glassPanel.setSize(frame.getSize());
frame.getLayeredPane().add(glassPanel, JLayeredPane.MODAL_LAYER);
glassPanel.revalidate();
glassPanel.setVisible(false);
// We need to resize the glass panel when its parent resizes.
frame.getLayeredPane().addComponentListener(
new java.awt.event.ComponentAdapter() {
@Override
public void componentResized(
java.awt.event.ComponentEvent evt) {
glassPanel.setSize(glassPanel.getParent().getSize());
glassPanel.revalidate();
}
});
closeButton.addActionListener(closeCurrentDialogue);
showControls = new HtmlJPanel(DialogueBoxController.class
.getResource("/jfreerails/client/view/game_controls.html"));
about = new HtmlJPanel(DialogueBoxController.class
.getResource("/jfreerails/client/view/about.htm"));
how2play = new HtmlJPanel(DialogueBoxController.class
.getResource("/jfreerails/client/view/how_to_play.htm"));
terrainInfo = new TerrainInfoJPanel();
stationInfo = new StationInfoJPanel();
javaProperties = new HtmlJPanel(ShowJavaProperties
.getPropertiesHtmlString());
Dimension d = javaProperties.getPreferredSize();
d.width += 50;
javaProperties.setPreferredSize(d);
newspaper = new NewsPaperJPanel();
selectWagons = new SelectWagonsJPanel();
selectEngine = new SelectEngineJPanel();
trainDialogueJPanel = new TrainDialogueJPanel();
}

setStationType

Class: jfreerails.controller.StationBuilder

Documentation

No documentation available

Source Code

public void setStationType(int ruleNumber) {
this.ruleNumber = ruleNumber;
}

Called Methods

No outgoing method calls

flush

Class: jfreerails.network.Connection2Server

Documentation

/** Flush the underlying stream. */

Source Code

/** Flush the underlying stream. */
void flush() throws IOException;

Called Methods

No outgoing method calls

unpackMove

Class: jfreerails.move.TrackMoveTransactionsGenerator

Documentation

No documentation available

Source Code

private void unpackMove(Move move) {
if (move instanceof ChangeTrackPieceMove) {
ChangeTrackPieceMove tm = (ChangeTrackPieceMove) move;
processMove(tm);
} else if (move instanceof CompositeMove) {
CompositeMove cm = (CompositeMove) move;
cm.getMoves();
ImList<Move> moves = cm.getMoves();
for (int i = 0; i < moves.size(); i++) {
unpackMove(moves.get(i));
}
}
}

actionPerformed

Class: jfreerails.client.view.SetTargetTicksPerSecondAction

Documentation

No documentation available

Source Code

public void actionPerformed(ActionEvent e) {
int speed2set = speed;
if (speed == 0) { // pausing/unpausing
speed2set = -1 * getTargetTicksPerSecond();
}
modelRoot.doMove(ChangeGameSpeedMove.getMove(modelRoot.getWorld(),
new GameSpeed(speed2set)));
}

getConversion

Class: jfreerails.world.terrain.TileTypeImpl

Documentation

No documentation available

Source Code

public ImList<Conversion> getConversion() {
return conversion;
}

Called Methods

No outgoing method calls

suite

Class: jfreerails.move.ChangeTrackPieceCompositeMoveTest

Documentation

No documentation available

Source Code

public static Test suite() {
TestSuite testSuite = new TestSuite(
ChangeTrackPieceCompositeMoveTest.class);
return testSuite;
}

Called Methods

No outgoing method calls

tryUndoMove

Class: jfreerails.move.ChangeProductionAtEngineShopMove

Documentation

No documentation available

Source Code

public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
return tryMove(w, after);
}

facing

Class: jfreerails.world.common.PositionOnTrack

Documentation

/**
* @return The direction the entity is facing.
*/

Source Code

/**
* @return The direction the entity is facing.
*/
public Step facing() {
return cameFrom.getOpposite();
}

nextStep

Class: jfreerails.util.Unknown

Documentation

No documentation available

Source Code

public void nextStep(int max) {
}

Called Methods

No outgoing method calls

getActivity

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public SpeedTimeAndStatus.TrainActivity getActivity() {
return activity;
}

Called Methods

No outgoing method calls

getLegalConfigurationsIterator

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

public Iterator<TrackConfiguration> getLegalConfigurationsIterator() {
throw new UnsupportedOperationException("Method not implemented yet!");
}

Called Methods

No outgoing method calls

abandonSearch

Class: jfreerails.controller.IncrementalPathFinder

Documentation

No documentation available

Source Code

public abstract void abandonSearch();

Called Methods

No outgoing method calls

equals

Class: jfreerails.move.ChangeTrackPieceMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof ChangeTrackPieceMove) {
ChangeTrackPieceMove m = (ChangeTrackPieceMove) o;
boolean fieldPointEqual = this.location.equals(m.location);
boolean fieldoldTrackPieceEqual = this.trackPieceBefore
.equals(m.trackPieceBefore);
boolean fieldnewTrackPieceEqual = this.trackPieceAfter
.equals(m.trackPieceAfter);
if (fieldPointEqual && fieldoldTrackPieceEqual
&& fieldnewTrackPieceEqual) {
return true;
}
return false;
}
return false;
}

getRightOfWay

Class: jfreerails.world.terrain.TerrainType

Documentation

No documentation available

Source Code

int getRightOfWay();

Called Methods

No outgoing method calls

getScaledImage

Class: jfreerails.client.renderer.RenderersRoot

Documentation

No documentation available

Source Code

Image getScaledImage(String relativeFilename, int height) throws IOException;

Called Methods

No outgoing method calls

testNewGame

Class: jfreerails.network.specifics.FreerailsClientWithLocalServerTest

Documentation

No documentation available

Source Code

public void testNewGame() {
assertEquals(0, server.countOpenConnections());
/* Connect 2 clients. */
FreerailsClient client0 = new FreerailsClient();
LogOnResponse response0 = client0
.connect(server, "client0", "password");
assertTrue(response0.isSuccessful());
FreerailsClient client1 = new FreerailsClient();
LogOnResponse response1 = client1
.connect(server, "client1", "password");
assertTrue(response1.isSuccessful());
assertEquals(2, server.countOpenConnections());
client0.update();
client1.update();
/* Start a new game. */
assertNull(client0.getWorld());
assertNull(client1.getWorld());
ImStringList mapNames = (ImStringList) client0
.getProperty(ClientProperty.MAPS_AVAILABLE);
final int commandID = 66;
Message2Server message2 = new NewGameMessage2Server(commandID, mapNames
.get(0));
client0.write(message2);
assertTrue(server.isNewPlayersAllowed());
server.update();
assertFalse("New players cannot be added once the game has started.",
server.isNewPlayersAllowed());
/*
* Note, the following would have happened anyway when client0.update();
* gets called.
*/
FreerailsSerializable obj = client0.read();
Message2Client cc = (Message2Client) obj;
client0.write(cc.execute(client0));
obj = client0.read();
MessageStatus status = (MessageStatus) obj;
assertTrue(status.isSuccessful());
assertEquals(commandID, status.getId());
/* The server should have sent a message2 that sets the world object. */
client0.update();
client1.update();
assertNotNull(client0.getWorld());
assertNotNull(client1.getWorld());
/* The server will not have read the players confirmation yet. */
assertFalse(server.isConfirmed(0));
assertFalse(server.isConfirmed(1));
server.update();
/* Now it will. */
assertTrue(server.isConfirmed(0));
assertTrue(server.isConfirmed(1));
/*
* The number of players on the world object should be the same as the
* number of players under the ClientControlInterface.CONNECTED_CLIENTS
* key
*/
int connectedPlayers = ((ImStringList) client0
.getProperty(ClientProperty.CONNECTED_CLIENTS)).size();
int playersOnWorldObject = client0.getWorld().getNumberOfPlayers();
assertEquals(connectedPlayers, playersOnWorldObject);
World w = client0.getWorld();
assertNotNull(w.getPlayer(0));
assertNotNull(w.getPlayer(1));
/*
* Now check that attempts to log on by new players are rejected.
*/
assertEquals(2, server.countOpenConnections());
FreerailsClient client = new FreerailsClient();
LogOnResponse response = client.connect(server, "Late player",
"password");
assertFalse(response.isSuccessful());
assertEquals(2, server.countOpenConnections());
}

sendCommand

Class: jfreerails.network.specifics.ServerCommandReceiver

Documentation

No documentation available

Source Code

void sendCommand(Message2Server c);

Called Methods

No outgoing method calls

end_CanOnlyBuildOnTheseTerrainTypes

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void end_CanOnlyBuildOnTheseTerrainTypes() throws SAXException {
legalTrackPlacement = new LegalTrackPlacement(terrainTypes,
LegalTrackPlacement.PlacementRule.ONLY_ON_THESE);
terrainTypes = null;
}

Called Methods

No outgoing method calls

update

Class: jfreerails.network.specifics.FreerailsClient

Documentation

/** Reads and deals with all outstanding messages from the server. */

Source Code

/** Reads and deals with all outstanding messages from the server. */
final public void update() {
try {
FreerailsSerializable[] messages = connection2Server
.readFromServer();
for (int i = 0; i < messages.length; i++) {
FreerailsSerializable message = messages[i];
processMessage(message);
}
connection2Server.flush();
clientUpdates();
} catch (IOException e) {
ReportBugTextGenerator.unexpectedException(e);
}
}

main

Class: jfreerails.move.ChangeTrackPieceMoveTest

Documentation

No documentation available

Source Code

public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}

monthEnd

Class: jfreerails.server.ServerGameModelImpl

Documentation

/** This is called at the start of each new month. */

Source Code

/** This is called at the start of each new month. */
private void monthEnd() {
calcSupplyAtStations.doProcessing();
CargoAtStationsGenerator cargoAtStationsGenerator = new CargoAtStationsGenerator();
cargoAtStationsGenerator.update(world, moveExecuter);
}

undoMove

Class: jfreerails.move.Move

Documentation

/**
* If <code>doMove</code> has just been executed on the specified world
* object, calling this method changes the state of the world object back to
* how it was before <code>doMove</code> was called.
*/

Source Code

/**
* If <code>doMove</code> has just been executed on the specified world
* object, calling this method changes the state of the world object back to
* how it was before <code>doMove</code> was called.
*/
MoveStatus undoMove(World w, FreerailsPrincipal p);

Called Methods

No outgoing method calls

isSetup

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

public boolean isSetup() {
return isSetup;
}

Called Methods

No outgoing method calls

unexpectedException

Class: jfreerails.controller.ReportBugTextGenerator

Documentation

No documentation available

Source Code

@SuppressWarnings("deprecation")
public static void unexpectedException(Exception e) {
ScreenHandler.exitFullScreenMode();
String str = genText(e);
System.err.print(str);
UnexpectedExceptionForm unexpectedExceptionForm = new UnexpectedExceptionForm();
unexpectedExceptionForm.setText(str);
unexpectedExceptionForm.setVisible(true);
if(!EventQueue.isDispatchThread()){
Thread.currentThread().stop();
}
}

getID

Class: jfreerails.network.specifics.SetPropertyMessage2Client

Documentation

No documentation available

Source Code

public int getID() {
return id;
}

Called Methods

No outgoing method calls

getCursorPosition

Class: jfreerails.client.renderer.BuildTrackController

Documentation

/** Utility method that gets the cursor position from the model root. */

Source Code

/** Utility method that gets the cursor position from the model root. */
private ImPoint getCursorPosition() {
ImPoint point = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.CURSOR_POSITION);
// Check for null & make a defensive copy
point = null == point ? new ImPoint() : point;
if (!modelRoot.getWorld().boundsContain(point.x, point.y)) {
throw new IllegalStateException(String.valueOf(point));
}
return point;
}

AbstractTileRenderer

Class: jfreerails.client.renderer.AbstractTileRenderer

Documentation

No documentation available

Source Code

AbstractTileRenderer(TerrainType t, int[] rgbValues) {
tileModel = t;
this.typeNumbers = rgbValues;
if (null == t) {
throw new NullPointerException();
}
if (null == rgbValues) {
throw new NullPointerException();
}
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (null == o) {
return false;
}
if (o instanceof PositionOnTrack) {
PositionOnTrack other = (PositionOnTrack) o;
if (other.cameFrom() == this.cameFrom()
&& other.getX() == this.getX()
&& other.getY() == this.getY()) {
return true;
}
return false;
}
return false;
}

getName

Class: jfreerails.world.player.PlayerPrincipal

Documentation

No documentation available

Source Code

public String getName() {
return name;
}

Called Methods

No outgoing method calls

testAddingElementAlreadyPresent

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

public void testAddingElementAlreadyPresent(){
underlying.addD1();
underlying.addD2(0, new Integer(1));
diffs.removeLastD2(0);
diffs.addD2(0, new Integer(1));
assertEquals(0, map.size());
}

setTerrainType

Class: jfreerails.client.view.TerrainInfoJPanel

Documentation

No documentation available

Source Code

public void setTerrainType(int typeNumber) {
TerrainType type = (TerrainType) w.get(SKEY.TERRAIN_TYPES, typeNumber);
String row = "<p>Right-of-Way costs $" + type.getRightOfWay()
+ " per mile. </p>";
String tableString = "";
int cargosProduced = type.getProduction().size();
int cargosConsumed = type.getConsumption().size();
int cargosConverted = type.getConversion().size();
if ((cargosProduced + cargosConsumed + cargosConverted) > 0) {
// if the terrain type produces, consumes, or converts anything.
tableString = "<table width=\"75%\" >";
if (cargosProduced != 0) {
tableString += "<tr> <td><strong>Supplies</strong></td> <td>&nbsp;</td> </tr>";
for (int i = 0; i < cargosProduced; i++) {
Production p = type.getProduction().get(i);
CargoType c = (CargoType) w.get(SKEY.CARGO_TYPES, p
.getCargoType());
String supply = String.valueOf(p.getRate()
/ WagonType.UNITS_OF_CARGO_PER_WAGON);
tableString += "<tr> <td>" + c.getDisplayName()
+ " </td><td>" + supply + "</td></tr>";
}
}
if (cargosConsumed != 0) {
tableString += "<tr> <td><strong>Demands</strong></td> <td>&nbsp;</td> </tr>";
for (int i = 0; i < cargosConsumed; i++) {
Consumption p = type.getConsumption().get(i);
CargoType c = (CargoType) w.get(SKEY.CARGO_TYPES, p
.getCargoType());
tableString += "<tr> <td>" + c.getDisplayName()
+ " </td><td>&nbsp;</td></tr>";
}
}
if (cargosConverted != 0) {
tableString += "<tr> <td><strong>Converts</strong></td> <td>&nbsp;</td> </tr>";
for (int i = 0; i < cargosConverted; i++) {
Conversion p = type.getConversion().get(i);
CargoType input = (CargoType) w.get(SKEY.CARGO_TYPES, p
.getInput());
CargoType output = (CargoType) w.get(SKEY.CARGO_TYPES, p
.getOutput());
tableString += "<tr> <td colspan=\"2\">"
+ input.getDisplayName() + " to "
+ output.getDisplayName() + "</td></tr>";
}
}
tableString += "</table> ";
}
String labelString = "<html>" + row + tableString + "</html>";
terrainDescription.setText(labelString);
terrainName.setText(type.getDisplayName());
Image tileIcon = rr.getTileViewWithNumber(typeNumber)
.getDefaultIcon();
terrainImage.setIcon(new ImageIcon(tileIcon));
repaint();
}

isDouble

Class: jfreerails.world.track.TrackRule

Documentation

No documentation available

Source Code

boolean isDouble();

Called Methods

No outgoing method calls

equals

Class: jfreerails.move.AddActiveEntityMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof AddActiveEntityMove))
return false;
final AddActiveEntityMove addActiveEntityMove = (AddActiveEntityMove) o;
if (index != addActiveEntityMove.index)
return false;
if (!activity.equals(addActiveEntityMove.activity))
return false;
if (!principal.equals(addActiveEntityMove.principal))
return false;
return true;
}

Called Methods

No outgoing method calls

toServer

Class: jfreerails.network.specifics.MovePrecommitter

Documentation

No documentation available

Source Code

void toServer(Move m) {
uncomitted.addLast(m);
precommitMoves();
}

readResolve

Class: jfreerails.world.track.TrackConfiguration

Documentation

No documentation available

Source Code

private Object readResolve() throws ObjectStreamException {
return TrackConfiguration.from9bitTemplate(this.configuration);
}

getTerrainTypeName

Class: jfreerails.world.terrain.TileTypeImpl

Documentation

No documentation available

Source Code

public String getTerrainTypeName() {
return terrainType;
}

Called Methods

No outgoing method calls

mouseExited

Class: jfreerails.client.view.StationPlacementCursor

Documentation

No documentation available

Source Code

@Override
public void mouseExited(MouseEvent e) {
stationRadiusRenderer.hide();
}

CalcNearestCity

Class: jfreerails.controller.CalcNearestCity

Documentation

No documentation available

Source Code

public CalcNearestCity(ReadOnlyWorld world, int x, int y) {
this.w = world;
this.x = x;
this.y = y;
}

Called Methods

No outgoing method calls

write

Class: jfreerails.util.FlowRateOutputStream

Documentation

No documentation available

Source Code

@Override
public void write(int b) throws IOException {
super.out.write(b);
totalByteSent++;
}

Called Methods

No outgoing method calls

add2Array

Class: jfreerails.util.ListXDDiffs

Documentation

No documentation available

Source Code

static int[] add2Array(int[] dim, int last) {
int[] array = new int[dim.length + 1];
for (int i = 0; i < dim.length; i++) {
array[i] = dim[i];
}
array[array.length - 1] = last;
return array;
}

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.view.TerrainInfoJPanel

Documentation

No documentation available

Source Code

public void setup(ReadOnlyWorld w, RenderersRoot vl) {
this.w = w;
this.rr = vl;
}

Called Methods

No outgoing method calls

markCompletelyDirty

Class: jfreerails.client.common.RepaintManagerForActiveRendering

Documentation

No documentation available

Source Code

@Override
public void markCompletelyDirty(JComponent aComponent) {
if (hasDifferentAncestor(aComponent)) {
super.markCompletelyDirty(aComponent);
} else {
numRepaintRequests++;
}
}

equals

Class: jfreerails.util.List2DDiff

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object obj) {
if (!(obj instanceof List2D))
return false;
return Lists.equals(this, (List2D)obj);
}

getProduction

Class: jfreerails.world.terrain.NullTerrainType

Documentation

No documentation available

Source Code

public ImList<Production> getProduction() {
return new ImList<Production>();
}

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.view.TrainSummaryJPanel

Documentation

No documentation available

Source Code

public void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
this.principal = modelRoot.getPrincipal();
this.w = modelRoot.getWorld();
trainListCellRenderer1 = new TrainListCellRenderer(modelRoot, vl);
trainListCellRenderer1.setHeight(15);
}

hashCode

Class: jfreerails.world.accounts.Receipt

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = amount.hashCode();
result = 29 * result + category.hashCode();
return result;
}

isStation

Class: jfreerails.world.track.TrackRule

Documentation

No documentation available

Source Code

boolean isStation();

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.terrain.Production

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Production))
return false;
final Production production = (Production) o;
if (cargoType != production.cargoType)
return false;
if (rate != production.rate)
return false;
return true;
}

Called Methods

No outgoing method calls

showMenu

Class: jfreerails.client.top.StationTypesPopup

Documentation

No documentation available

Source Code

public void showMenu(Component invoker, int x, int y, Point tile) {
tileToBuildStationOn = tile;
super.show(invoker, x, y);
}

Called Methods

No outgoing method calls

add

Class: jfreerails.world.top.World

Documentation

/**
* Appends the specified element to the end of the specified list and returns
* the index that can be used to retrieve it.
*/

Source Code

/**
* Appends the specified element to the end of the specified list and returns
* the index that can be used to retrieve it.
*/
int add(FreerailsPrincipal principal, KEY key, FreerailsSerializable element);

Called Methods

No outgoing method calls

testPathAsVectors1

Class: jfreerails.controller.PathOnTrackFinderTest

Documentation

No documentation available

Source Code

public void testPathAsVectors1() {
Step[] path = { EAST, EAST, SOUTH_EAST };
ImPoint start = new ImPoint(5, 5);
ImPoint end = Step.move(start, path);
producer.buildTrack(start, path);
try {
pathFinder.setupSearch(start, end);
pathFinder.search(-1);
assertEquals(IncrementalPathFinder.PATH_FOUND, pathFinder
.getStatus());
Step[] pathFound = pathFinder.pathAsVectors();
assertTrue(Arrays.equals(path, pathFound));
} catch (PathNotFoundException e) {
fail();
}
}

setAppropriateScale

Class: jfreerails.client.view.NetWorthGraphJPanel

Documentation

/**
* <p>
* Sets the value of scaleMax subject to the following constraints.
* </P>
* <p>
* (1) scaleMax >= max, where max is the max net worth value.
* </p>
* <p>
* (2) (scaleMax % 4) == 0
* </p>
* <p>
* (3) if max >= 1,000, then (scaleMax % 4,000) == 0
* </p>
* <p>
* (4) if max >= 1,000,000, then (scaleMax % 4,000,000) == 0
* </p>
* <p>
* (5) if max >= 1,000,000,000, then (scaleMax % 4,000,000,000) == 0
* </p>
*/

Source Code

/**
* <p>
* Sets the value of scaleMax subject to the following constraints.
* </P>
* <p>
* (1) scaleMax >= max, where max is the max net worth value.
* </p>
* <p>
* (2) (scaleMax % 4) == 0
* </p>
* <p>
* (3) if max >= 1,000, then (scaleMax % 4,000) == 0
* </p>
* <p>
* (4) if max >= 1,000,000, then (scaleMax % 4,000,000) == 0
* </p>
* <p>
* (5) if max >= 1,000,000,000, then (scaleMax % 4,000,000,000) == 0
* </p>
*/
private void setAppropriateScale() {
long max = 0;
for (int i = 0; i < companies.size(); i++) {
CompanyDetails company = companies.get(i);
for (int year = 0; year < 100; year++) {
long value = company.value[year];
if (value > max) {
max = value;
}
}
}
long increment = 1;
while (scaleMax < max) {
scaleMax = increment;
if (scaleMax < max) {
scaleMax += increment;
int loopCount = 0;
while (scaleMax < max && loopCount < 3) {
scaleMax += increment * 2;
loopCount++;
}
}
increment = increment * 10;
}
/*
* Make sure that if the scale is in k/m/b that each of the quarter
* scales will be divisible by k/m/b.
*/
increment = 1;
for (int i = 0; i < 3; i++) {
increment = increment * 1000;
if (scaleMax >= 8 * increment && scaleMax < 12 * increment) {
scaleMax = 12 * increment;
} else if (scaleMax >= 4 * increment && scaleMax < 8 * increment) {
scaleMax = 8 * increment;
} else if (scaleMax >= 1 * increment && scaleMax < 4 * increment) {
scaleMax = 4 * increment;
}
}
if (scaleMax < 100) {
scaleMax = 100;
}
long quarterScale = scaleMax / 4;
yAxisLabel1.setText(getYScaleString(quarterScale));
yAxisLabel2.setText(getYScaleString(quarterScale * 2));
yAxisLabel3.setText(getYScaleString(quarterScale * 3));
yAxisLabel4.setText(getYScaleString(quarterScale * 4));
}

setupConfigurations

Class: jfreerails.world.track.TrackConfiguration

Documentation

No documentation available

Source Code

private static ArrayList<TrackConfiguration> setupConfigurations() {
ArrayList<TrackConfiguration> configurations = new ArrayList<TrackConfiguration>(
512);
for (int i = 0; i < 512; i++) {
configurations.add(i, new TrackConfiguration(i));
}
return configurations;
}

Called Methods

No outgoing method calls

startElement

Class: jfreerails.server.parser.Track_TilesParser

Documentation

No documentation available

Source Code

public void startElement(java.lang.String ns, java.lang.String name,
java.lang.String qname, org.xml.sax.Attributes attrs)
throws SAXException {
dispatch(true);
context.push(new Object[] { qname,
new org.xml.sax.helpers.AttributesImpl(attrs) });
if ("CanOnlyBuildOnTheseTerrainTypes".equals(qname)) {
handler.start_CanOnlyBuildOnTheseTerrainTypes(attrs);
} else if ("ListOfTrackPieceTemplates".equals(qname)) {
handler.start_ListOfTrackPieceTemplates(attrs);
} else if ("ListOfLegalRoutesAcrossNode".equals(qname)) {
handler.start_ListOfLegalRoutesAcrossNode(attrs);
} else if ("LegalRouteAcrossNode".equals(qname)) {
handler.handle_LegalRouteAcrossNode(attrs);
} else if ("CannotBuildOnTheseTerrainTypes".equals(qname)) {
handler.start_CannotBuildOnTheseTerrainTypes(attrs);
} else if ("TrackType".equals(qname)) {
handler.start_TrackType(attrs);
} else if ("TerrainType".equals(qname)) {
handler.handle_TerrainType(attrs);
} else if ("Tiles".equals(qname)) {
handler.start_Tiles(attrs);
} else if ("TrackPieceTemplate".equals(qname)) {
handler.start_TrackPieceTemplate(attrs);
} else if ("TrackSet".equals(qname)) {
handler.start_TrackSet(attrs);
}
}

listUpdated

Class: jfreerails.client.view.StationInfoJPanel

Documentation

No documentation available

Source Code

public void listUpdated(KEY key, int index, FreerailsPrincipal principal) {
if (modelRoot.getPrincipal().equals(principal))
reactToUpdate(key, index, false);
}

calcPositions

Class: jfreerails.client.renderer.TrainRenderer

Documentation

/**
* Calculates the positions of the engine and each wagon on the map.
* Intended to be used for rendering trains, for rendering highlights
* around trains, and for determining if a mouse click was on a train.
*
* @param train
* @param s
* @return List of positions, one entry for the engine and one for each
* wagon.
*/

Source Code

/**
* Calculates the positions of the engine and each wagon on the map.
* Intended to be used for rendering trains, for rendering highlights
* around trains, and for determining if a mouse click was on a train.
*
* @param train
* @param s
* @return List of positions, one entry for the engine and one for each
* wagon.
*/
public List<Entry<Point, Step>> calcPositions(TrainModel train, TrainPositionOnMap s) {
List<Entry<Point, Step>> positions = new ArrayList<>(train.getLength() + 1);
FreerailsPathIterator it = s.path();
PathWalker pw = new PathWalkerImpl(it);
// Engine + wagons
for (int i = 0; i < train.getNumberOfWagons() + 1; i++) {
IntLine wagon = new IntLine();
IntLine line = new IntLine();
pw.stepForward(16);
boolean firstIteration = true;
while (pw.hasNext()) {
pw.nextSegment(line);
if (firstIteration) {
wagon.x1 = line.x1;
wagon.y1 = line.y1;
firstIteration = false;
}
}
wagon.x2 = line.x2;
wagon.y2 = line.y2;
Step v = Step
.getNearestVector(wagon.x2 - wagon.x1, wagon.y2 - wagon.y1);
Point wagonCenter = new Point((wagon.x2 + wagon.x1) / 2,
(wagon.y2 + wagon.y1) / 2);
positions.add(new AbstractMap.SimpleImmutableEntry<>(wagonCenter, v));
// The gap between wagons
pw.stepForward(8);
while (pw.hasNext()) {
pw.nextSegment(line);
}
}
return positions;
}

equals

Class: jfreerails.move.AddItemToSharedListMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof AddItemToSharedListMove) {
AddItemToSharedListMove test = (AddItemToSharedListMove) o;
if (!this.item.equals(test.getAfter())) {
return false;
}
if (this.index != test.index) {
return false;
}
if (this.listKey != test.listKey) {
return false;
}
return true;
}
return false;
}

getCargoType

Class: jfreerails.world.cargo.CargoBatch

Documentation

No documentation available

Source Code

public int getCargoType() {
return cargoType;
}

Called Methods

No outgoing method calls

pathAsVectors

Class: jfreerails.controller.PathOnTrackFinder

Documentation

No documentation available

Source Code

public Step[] pathAsVectors() {
int[] pathAsInts = pathFinder.retrievePath().toArray();
Step[] vectors = new Step[pathAsInts.length];
int x = startPoint.x;
int y = startPoint.y;
for (int i = 0; i < pathAsInts.length; i++) {
PositionOnTrack p2 = new PositionOnTrack(pathAsInts[i]);
vectors[i] = Step.getInstance(p2.getX() - x, p2.getY() - y);
x = p2.getX();
y = p2.getY();
}
return vectors;
}

getActivity

Class: jfreerails.world.common.ActivityIterator

Documentation

No documentation available

Source Code

Activity getActivity();

Called Methods

No outgoing method calls

testToString

Class: jfreerails.world.track.TrackConfigurationTest

Documentation

No documentation available

Source Code

public void testToString() {
TrackConfiguration a = TrackConfiguration.getFlatInstance("100010000");
assertEquals("tile center, north west", a.toString());
a = TrackConfiguration.getFlatInstance(Step.NORTH_WEST);
assertEquals("no tile center, north west", a.toString());
a = TrackConfiguration.getFlatInstance("000010000");
assertEquals("tile center", a.toString());
a = TrackConfiguration.getFlatInstance("000000000");
assertEquals("no tile center", a.toString());
// Check that no two track configurations have the same String
// representation.
HashSet<String> strings = new HashSet<String>();
for (int i = 0; i < 512; i++) {
TrackConfiguration test = TrackConfiguration.from9bitTemplate(i);
String toString = test.toString();
if (strings.contains(toString)) {
fail(toString + " " + i);
}
strings.add(toString);
}
}

ModelRootImpl

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public ModelRootImpl() {
properties.put(Property.CURSOR_POSITION, new ImPoint());
properties.put(Property.SHOW_STATION_NAMES, Boolean.TRUE);
properties.put(Property.SHOW_CARGO_AT_STATIONS, Boolean.TRUE);
properties.put(Property.SHOW_STATION_BORDERS, Boolean.TRUE);
properties.put(Property.CURSOR_MODE, Value.BUILD_TRACK_CURSOR_MODE);
properties.put(Property.PREVIOUS_CURSOR_MODE,
Value.BUILD_TRACK_CURSOR_MODE);
properties.put(Property.SERVER, "server details not set!");
properties.put(Property.PLAY_SOUNDS, Boolean.TRUE);
properties.put(Property.IGNORE_KEY_EVENTS, Boolean.FALSE);
properties.put(Property.TIME, new Double(0));
properties.put(Property.TRACK_BUILDER_MODE,
TrackMoveProducer.BuildMode.BUILD_TRACK);
properties.put(Property.SAVED_GAMES_LIST, new ImStringList());
addPropertyChangeListener(SoundManager.getSoundManager());
}

init

Class: jfreerails.network.specifics.SimpleServerGameModel

Documentation

No documentation available

Source Code

public void init(MoveReceiver moveExecuter) {
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.track.LegalTrackPlacement

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof LegalTrackPlacement) {
LegalTrackPlacement test = (LegalTrackPlacement) o;
if (this.placementRule.equals(test.getPlacementRule())
&& this.terrainTypes.equals(test.terrainTypes)) {
return true;
}
return false;
}
return false;
}

get9bitTemplate

Class: jfreerails.world.common.FlatTrackTemplate

Documentation

/**
* @return the integer representing the vector(s) of this object.
*/

Source Code

/**
* @return the integer representing the vector(s) of this object.
*/
int get9bitTemplate();

Called Methods

No outgoing method calls

testMove

Class: jfreerails.move.ChangeProductionAtEngineShopMoveTest

Documentation

No documentation available

Source Code

@Override
public void testMove() {
before = new ImList<PlannedTrain>();
ChangeProductionAtEngineShopMove m;
// Should fail because current production at station 0 is null;
m = new ChangeProductionAtEngineShopMove(after, before, 0,
MapFixtureFactory.TEST_PRINCIPAL);
assertTryMoveFails(m);
assertDoMoveFails(m);
// Should fail because station 6 does not exist.
m = new ChangeProductionAtEngineShopMove(before, after, 6,
MapFixtureFactory.TEST_PRINCIPAL);
assertTryMoveFails(m);
assertDoMoveFails(m);
// Should go through
m = new ChangeProductionAtEngineShopMove(before, after, 0,
MapFixtureFactory.TEST_PRINCIPAL);
assertTryMoveIsOk(m);
assertDoMoveIsOk(m);
assertTryUndoMoveIsOk(m);
assertUndoMoveIsOk(m);
// It should not be repeatable.
assertOkButNotRepeatable(m);
assertSurvivesSerialisation(m);
}

testEqualsObject

Class: jfreerails.world.track.TrackSectionTest

Documentation

No documentation available

Source Code

public void testEqualsObject() {
TrackSection a = new TrackSection(Step.EAST, new ImPoint(10, 5));
TrackSection b = new TrackSection(Step.WEST, new ImPoint(11, 5));
assertEquals(a, a);
assertEquals(b, b);
assertEquals(a, b);
assertEquals(b, a);
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.util.ListKey

Documentation

No documentation available

Source Code

@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(listID);
sb.append(" ");
sb.append(type);
sb.append(" index ");
for (int i = 0; i < index.length; i++) {
sb.append("[");
sb.append(index[i]);
sb.append("]");
}
return sb.toString();
}

Called Methods

No outgoing method calls

getTileViewWithNumber

Class: jfreerails.client.top.QuickRGBTileRendererList

Documentation

No documentation available

Source Code

public TileRenderer getTileViewWithNumber(int i) {
throw new UnsupportedOperationException();
}

Called Methods

No outgoing method calls

testSetIntIntIntT

Class: jfreerails.util.List3DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List3DDiff.set(int, int, int, T)'
*/
public void testSetIntIntIntT() {
underlying.addD1();
underlying.addD2(0);
underlying.addD3(0,0, new Integer(1));
assertEquals(new Integer(1), diffs.get(0, 0, 0));
diffs.addD3(0,0, new Integer(2));
assertEquals(new Integer(2), diffs.get(0, 0, 1));
diffs.set(0,0,0, new Integer(11));
assertEquals(new Integer(11), diffs.get(0, 0, 0));
diffs.set(0,0,1, new Integer(22));
assertEquals(new Integer(22), diffs.get(0, 0, 1));
}

compareTo

Class: jfreerails.world.common.ImPoint

Documentation

No documentation available

Source Code

public int compareTo(ImPoint o) {
if (o.y != y)
return y - o.y;
else
return x - o.x;
}

Called Methods

No outgoing method calls

BalanceSheetHtmlJPanel

Class: jfreerails.client.view.BalanceSheetHtmlJPanel

Documentation

No documentation available

Source Code

public BalanceSheetHtmlJPanel() {
super();
URL url = BalanceSheetHtmlJPanel.class
.getResource("/jfreerails/client/view/balance_sheet.htm");
template = loadText(url);
}

SupplyAtStation

Class: jfreerails.world.station.SupplyAtStation

Documentation

No documentation available

Source Code

public SupplyAtStation(int[] cargoWaiting) {
supply = new ImInts(cargoWaiting);
}

Called Methods

No outgoing method calls

getLength

Class: jfreerails.world.train.TrainModel

Documentation

No documentation available

Source Code

public int getLength() {
return (1 + wagonTypes.size()) * WAGON_LENGTH; // Engine + wagons.
}

getF

Class: jfreerails.controller.OpenList

Documentation

No documentation available

Source Code

int getF(int node) {
int f = map.get(node).f;
return f;
}

Called Methods

No outgoing method calls

getY

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

public int getY() {
return y;
}

Called Methods

No outgoing method calls

getState

Class: jfreerails.world.train.CompositeSpeedAgainstTime

Documentation

No documentation available

Source Code

public SpeedTimeAndStatus getState(final double dt) {
checkT(dt);
double acceleration;
SpeedTimeAndStatus.TrainActivity activity = SpeedTimeAndStatus.TrainActivity.READY;
double s = 0;
double speed;
TandI tai = getIndex(dt);
SpeedAgainstTime acc = values.get(tai.i);
speed = acc.calcV(tai.offset);
acceleration = acc.calcA(tai.offset);
s = acc.calcS(tai.offset);
return new SpeedTimeAndStatus(acceleration, activity, dt, s, speed);
}

itemRemoved

Class: jfreerails.client.view.TrainDialogueJPanel

Documentation

No documentation available

Source Code

public void itemRemoved(KEY key, int index, FreerailsPrincipal p) {
}

Called Methods

No outgoing method calls

LoadGameMessage2Server

Class: jfreerails.network.specifics.LoadGameMessage2Server

Documentation

No documentation available

Source Code

public LoadGameMessage2Server(int id, String s) {
this.id = id;
this.filename = s;
}

Called Methods

No outgoing method calls

findCurrentMotion

Class: jfreerails.controller.TrainAccessor

Documentation

No documentation available

Source Code

public TrainMotion findCurrentMotion(double time) {
ActivityIterator ai = w.getActivities(p, id);
ai.gotoLastActivity();
while (ai.getStartTime() > time && ai.hasPrevious()) {
ai.previousActivity();
}
return (TrainMotion) ai.getActivity();
}

getFirstStationID

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

/**
* Since stations can be removed, we should not assume that station 0
* exists: this method returns the id of the first station that exists.
*
*/

Source Code

/**
* Since stations can be removed, we should not assume that station 0
* exists: this method returns the id of the first station that exists.
*
*/
private int getFirstStationID() {
NonNullElements stations = new NonNullElements(KEY.STATIONS, modelRoot
.getWorld(), modelRoot.getPrincipal());
if (stations.next()) {
return stations.getIndex();
}
throw new NoSuchElementException();
}

wagonTypesJListMouseClicked

Class: jfreerails.client.view.SelectWagonsJPanel

Documentation

No documentation available

Source Code

private void wagonTypesJListMouseClicked(java.awt.event.MouseEvent evt) { // GEN-FIRST:event_wagonTypesJListMouseClicked
// Add your handling code here:
addwagon();
} // GEN-LAST:event_wagonTypesJListMouseClicked

getTileViewList

Class: jfreerails.client.top.RenderersRootImpl

Documentation

No documentation available

Source Code

public TileRendererList getTileViewList() {
return this.tiles;
}

Called Methods

No outgoing method calls

paintComponent

Class: experimental.AnimationExpt

Documentation

No documentation available

Source Code

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
long l = System.currentTimeMillis();
String str = String.valueOf(l);
g.drawString(str, 100, 100);
}

Called Methods

No outgoing method calls

add

Class: jfreerails.util.List1D

Documentation

No documentation available

Source Code

int add(T element);

Called Methods

No outgoing method calls

setCursorMessage

Class: jfreerails.client.renderer.BuildTrackController

Documentation

/** Utility method that sets the CURSOR_MESSAGE property on the model root. */

Source Code

/** Utility method that sets the CURSOR_MESSAGE property on the model root. */
private void setCursorMessage(String s) {
modelRoot.setProperty(ModelRoot.Property.CURSOR_MESSAGE, s);
}

validate

Class: jfreerails.client.renderer.TrackPieceRendererList

Documentation

No documentation available

Source Code

public boolean validate(ReadOnlyWorld w) {
boolean okSoFar = true;
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
Iterator<TrackConfiguration> legalConfigurationsIterator = trackRule
.getLegalConfigurationsIterator();
TrackPieceRenderer trackPieceView = this.getTrackPieceView(i);
if (null == trackPieceView) {
logger
.warning("No track piece view for the following track type: "
+ trackRule.getTypeName());
return false;
}
while (legalConfigurationsIterator.hasNext()) {
TrackConfiguration trackConfig = legalConfigurationsIterator
.next();
int trackGraphicsNo = trackConfig.getTrackGraphicsID();
Image img = trackPieceView.getTrackPieceIcon(trackGraphicsNo);
if (null == img) {
logger
.warning("No track piece image for the following track type: "
+ trackRule.getTypeName()
+ ", with configuration: "
+ trackGraphicsNo);
okSoFar = false;
}
}
}
return okSoFar;
}

incrementRunningTotal

Class: jfreerails.world.top.ItemsTransactionAggregator

Documentation

No documentation available

Source Code

@Override
protected void incrementRunningTotal(int transactionID) {
super.incrementRunningTotal(transactionID);
Transaction t = w.getTransaction(principal, transactionID);
AddItemTransaction addItemTransaction = (AddItemTransaction) t;
quantityRunningTotal += addItemTransaction.getQuantity();
}

getInstance

Class: jfreerails.world.track.FreerailsTile

Documentation

No documentation available

Source Code

public static FreerailsTile getInstance(int terrainType) {
FreerailsTile tile = new FreerailsTile(terrainType);
if (instances.containsKey(tile)) {
return instances.get(tile);
}
instances.put(tile, tile);
return tile;
}

Called Methods

No outgoing method calls

testChangingMap

Class: jfreerails.move.WorldDiffsMoveTest

Documentation

No documentation available

Source Code

public void testChangingMap() {
diffs.setTile(4, 0, city1);
diffs.setTile(8, 5, city2);
runTests();
}

storeTotalIfAppropriate

Class: jfreerails.world.top.TransactionAggregator

Documentation

No documentation available

Source Code

private void storeTotalIfAppropriate(int timeIndex) {
if (timeIndex > 0) {
storeRunningTotal(timeIndex - 1);
}
}

flush

Class: jfreerails.util.CompressedOutputStream

Documentation

No documentation available

Source Code

@Override
public void flush() throws IOException {
int compSize = 0;
boolean sendCompressed;
if (writeIndex > 150) {
deflater.reset();
deflater.setInput(buffer, 0, writeIndex);
deflater.finish();
if (compBuffer.length < writeIndex * 2 + 40960) {
compBuffer = new byte[writeIndex * 2 + 40960];
}
compSize = deflater.deflate(compBuffer);
if (compSize <= 0) {
throw new IOException("Compression exception");
}
sendCompressed = compSize < writeIndex;
} else {
sendCompressed = false;
}
if (sendCompressed) {
super.out.write(1);
super.out.write(writeIndex >> 24 & 0xff);
super.out.write(writeIndex >> 16 & 0xff);
super.out.write(writeIndex >> 8 & 0xff);
super.out.write(writeIndex & 0xff);
super.out.write(compSize >> 24 & 0xff);
super.out.write(compSize >> 16 & 0xff);
super.out.write(compSize >> 8 & 0xff);
super.out.write(compSize & 0xff);
super.out.write(compBuffer, 0, compSize);
super.out.flush();
writeIndex = 0;
} else if (writeIndex > 0) {
super.out.write(0);
super.out.write(writeIndex >> 24 & 0xff);
super.out.write(writeIndex >> 16 & 0xff);
super.out.write(writeIndex >> 8 & 0xff);
super.out.write(writeIndex & 0xff);
super.out.write(buffer, 0, writeIndex);
super.out.flush();
writeIndex = 0;
}
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.terrain.Consumption

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Consumption))
return false;
final Consumption consumption = (Consumption) o;
if (cargoType != consumption.cargoType)
return false;
if (prerequisite != consumption.prerequisite)
return false;
return true;
}

Called Methods

No outgoing method calls

ignorableWhitespace

Class: jfreerails.server.parser.Track_TilesParser

Documentation

No documentation available

Source Code

public void ignorableWhitespace(char[] chars, int start, int len)
throws SAXException {
}

Called Methods

No outgoing method calls

doMove

Class: jfreerails.move.ChangeProductionAtEngineShopMove

Documentation

No documentation available

Source Code

public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryDoMove(w, p);
if (status.isOk()) {
StationModel station = (StationModel) w.get(principal,
KEY.STATIONS, stationNumber);
station = new StationModel(station, this.after);
w.set(principal, KEY.STATIONS, stationNumber, station);
}
return status;
}

testBug1384249

Class: jfreerails.client.view.TrainScheduleJPanelTest

Documentation

No documentation available

Source Code

/*
* [ 1384249 ] Unexpected Exception: TrainScheduleJPanel.java line 661
*/
public void testBug1384249(){
}

Called Methods

No outgoing method calls

TrackPieceRendererList

Class: jfreerails.client.renderer.TrackPieceRendererList

Documentation

No documentation available

Source Code

public TrackPieceRendererList(ReadOnlyWorld w, ImageManager imageManager,
FreerailsProgressMonitor pm) throws IOException {
// Setup progress monitor..
pm.nextStep(w.size(SKEY.TRACK_RULES));
int progress = 0;
pm.setValue(progress);
int numberOfTrackTypes = w.size(SKEY.TRACK_RULES);
trackPieceViewArray = new TrackPieceRenderer[numberOfTrackTypes];
for (int i = 0; i < numberOfTrackTypes; i++) {
trackPieceViewArray[i] = new TrackPieceRendererImpl(w,
imageManager, i);
pm.setValue(++progress);
}
}

addSplitMoveReceiver

Class: jfreerails.network.specifics.MoveChainFork

Documentation

No documentation available

Source Code

public void addSplitMoveReceiver(MoveReceiver moveReceiver) {
if (null == moveReceiver) {
throw new NullPointerException();
}
splitMoveReceivers.add(moveReceiver);
}

Called Methods

No outgoing method calls

ImHashSet

Class: jfreerails.world.common.ImHashSet

Documentation

No documentation available

Source Code

public ImHashSet(E... values) {
this.hashSet = new HashSet<E>();
for (E e : values) {
hashSet.add(e);
}
}

Called Methods

No outgoing method calls

paint

Class: jfreerails.client.common.Painter

Documentation

No documentation available

Source Code

void paint(Graphics2D g);

Called Methods

No outgoing method calls

getDefaultErrorHandler

Class: jfreerails.server.parser.Track_TilesParser

Documentation

No documentation available

Source Code

private org.xml.sax.ErrorHandler getDefaultErrorHandler() {
return new org.xml.sax.ErrorHandler() {
public void error(org.xml.sax.SAXParseException ex)
throws SAXException {
if (context.isEmpty()) {
logger.severe("Missing DOCTYPE.");
}
throw ex;
}
public void fatalError(org.xml.sax.SAXParseException ex)
throws SAXException {
throw ex;
}
public void warning(org.xml.sax.SAXParseException ex)
throws SAXException {
// ignore
}
};
}

Called Methods

No outgoing method calls

paintRect

Class: jfreerails.client.renderer.ZoomedOutMapRenderer

Documentation

No documentation available

Source Code

public void paintRect(Graphics g, Rectangle visibleRect) {
renderOffScreenImage();
g.drawImage(mapImage, 0, 0, null);
}

writeToClient

Class: jfreerails.network.LocalConnection

Documentation

No documentation available

Source Code

public void writeToClient(FreerailsSerializable object) throws IOException {
if (status.isOpen()) {
synchronized (fromServer) {
fromServer.write(object);
fromServer.notifyAll();
}
} else {
throw new IOException();
}
}

TerrainLayer

Class: jfreerails.client.renderer.TerrainLayer

Documentation

No documentation available

Source Code

public TerrainLayer(ReadOnlyWorld world, TileRendererList tiles) {
this.w = world;
this.tiles = tiles;
}

Called Methods

No outgoing method calls

setPathToReadFrom

Class: jfreerails.client.common.ImageManager

Documentation

No documentation available

Source Code

void setPathToReadFrom(String s);

Called Methods

No outgoing method calls

writeToServer

Class: jfreerails.network.Connection2Server

Documentation

/** Sends the specified object to the server. */

Source Code

/** Sends the specified object to the server. */
void writeToServer(FreerailsSerializable object) throws IOException;

Called Methods

No outgoing method calls

getRGB

Class: jfreerails.world.terrain.TerrainType

Documentation

No documentation available

Source Code

int getRGB();

Called Methods

No outgoing method calls

CargoAtStationsGenerator

Class: jfreerails.server.CargoAtStationsGenerator

Documentation

No documentation available

Source Code

public CargoAtStationsGenerator() {
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.train.ImmutableSchedule

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof ImmutableSchedule) {
ImmutableSchedule test = (ImmutableSchedule) o;
return this.hasPriorityOrders == test.hasPriorityOrders
&& this.nextScheduledOrder == test.nextScheduledOrder
&& this.orders.equals(test.orders);
}
return false;
}

removeLastD1

Class: jfreerails.util.List2DImpl

Documentation

No documentation available

Source Code

public int removeLastD1() {
int last = elementData.size() -1;
if(sizeD2(last) != 0)
throw new IllegalStateException(String.valueOf(last));
elementData.remove(last);
return last;
}

prepare2HostNetworkGame

Class: jfreerails.launcher.Launcher

Documentation

/** Starts a thread listening for new connections. */

Source Code

/** Starts a thread listening for new connections. */
private void prepare2HostNetworkGame(int port) throws IOException {
loadProps();
if (isNewGame()) {
initServer();
}
InetConnectionAccepter accepter = new InetConnectionAccepter(port,
server);
/*
* Note, the thread's name gets set in the run method so there is no
* point setting it here.
*/
Thread t = new Thread(accepter);
t.start();
CardLayout cl = (CardLayout) jPanel1.getLayout();
cl.show(jPanel1, "3");
currentPage = 3;
}

end_TrackPieceTemplate

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* A container element end event handling method.
*/

Source Code

/**
* A container element end event handling method.
*/
void end_TrackPieceTemplate() throws SAXException;

Called Methods

No outgoing method calls

get

Class: jfreerails.util.List1D

Documentation

No documentation available

Source Code

T get(int i);

Called Methods

No outgoing method calls

getBuildMode

Class: jfreerails.client.renderer.BuildTrackController

Documentation

No documentation available

Source Code

private TrackMoveProducer.BuildMode getBuildMode() {
TrackMoveProducer.BuildMode mode;
mode = (TrackMoveProducer.BuildMode) modelRoot
.getProperty(ModelRoot.Property.TRACK_BUILDER_MODE);
return mode;
}

assertConnectClientsEquals

Class: jfreerails.network.specifics.FreerailsClientTest

Documentation

No documentation available

Source Code

private void assertConnectClientsEquals(FreerailsClient client,
ImStringList expectedPlayerNames) throws IOException,
InterruptedException {
Message2Client message2Client = (Message2Client) client.read();
message2Client.execute(client);
ImStringList actualPlayerNames = (ImStringList) client
.getProperty(ClientProperty.CONNECTED_CLIENTS);
assertNotNull(actualPlayerNames);
assertEquals(expectedPlayerNames, actualPlayerNames);
}

start_Tile

Class: jfreerails.server.parser.CargoAndTerrainHandler

Documentation

/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/

Source Code

/**
* A container element start event handling method.
*
* @param meta
* attributes
*
*/
public void start_Tile(final Attributes meta) throws SAXException;

Called Methods

No outgoing method calls

StationModel

Class: jfreerails.world.station.StationModel

Documentation

No documentation available

Source Code

public StationModel() {
this.name = "No name";
x = 0;
y = 0;
this.demand = new Demand4Cargo(new boolean[0]);
this.supply = new SupplyAtStation(new int[0]);
this.converted = new ConvertedAtStation(new int[0]);
production = new ImList<PlannedTrain>();
this.cargoBundleNumber = 0;
}

Called Methods

No outgoing method calls

getStatus

Class: jfreerails.controller.PathOnTrackFinder

Documentation

No documentation available

Source Code

public int getStatus() {
return pathFinder.getStatus();
}

fromServer

Class: jfreerails.network.specifics.MovePrecommitter

Documentation

/** Indicates that the server has processed a move we sent. */

Source Code

/** Indicates that the server has processed a move we sent. */
void fromServer(MoveStatus ms) {
precommitMoves();
if (precomitted.size() > 0) {
Move m = (Move) precomitted.removeFirst();
if (!ms.ok) {
logger.info("Move rejected by server: " + ms.message);
MoveStatus undoStatus = m.undoMove(w, Player.AUTHORITATIVE);
if (!undoStatus.ok) {
throw new IllegalStateException();
}
} else {
logger.finest("Move accepted by server: " + m.toString());
}
} else {
if (!ms.ok) {
logger.fine("Clear the blockage " + ms.message);
uncomitted.removeFirst();
precommitMoves();
} else {
throw new IllegalStateException();
}
}
}

condition

Class: jfreerails.controller.FinancialDataGatherer

Documentation

No documentation available

Source Code

@Override
protected boolean condition(int transactionID) {
// We'll do the work when incrementRunningTotal gets called.
return true;
}

Called Methods

No outgoing method calls

updateTarget

Class: jfreerails.controller.TrainStopsHandler

Documentation

/**
* Issues a ChangeTrainScheduleMove to set the train to move to the next
* station.
*/

Source Code

/**
* Issues a ChangeTrainScheduleMove to set the train to move to the next
* station.
*/
public void updateTarget() {
scheduledStop();
}

hashCode

Class: jfreerails.world.common.ImList

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return elementData.length;
}

Called Methods

No outgoing method calls

main

Class: jfreerails.world.top.NonNullElementsTest

Documentation

No documentation available

Source Code

public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}

removeLastD3

Class: jfreerails.util.List3DImpl

Documentation

No documentation available

Source Code

public T removeLastD3(int d1, int d2) {
ArrayList<T> dim3 = elementData.get(d1).get(d2);
int last = dim3.size()-1;
T element = dim3.get(last);
dim3.remove(last);
return element;
}

Called Methods

No outgoing method calls

getID

Class: jfreerails.controller.Message2Server

Documentation

No documentation available

Source Code

int getID();

Called Methods

No outgoing method calls

refresh

Class: jfreerails.client.renderer.ZoomedOutMapRenderer

Documentation

/**
* Redraw the whole map onto a new buffer.
*/

Source Code

/**
* Redraw the whole map onto a new buffer.
*/
private void refresh() {
isDirty = true;
/* free up memory used by the old image */
if (mapImage != null) {
mapImage.flush();
}
if (one2oneImage != null) {
one2oneImage.flush();
}
// if (mapGraphics != null) {
// mapGraphics.dispose();
// }
/* generate a 1:1 map of the terrain layer */
one2oneImage = defaultConfiguration.createCompatibleImage(mapWidth,
mapHeight, Transparency.TRANSLUCENT);
mapImage = defaultConfiguration.createCompatibleImage(imageWidth,
imageHeight, Transparency.OPAQUE);
Point tile = new Point();
for (tile.x = mapX; tile.x < mapWidth + mapX; tile.x++) {
for (tile.y = mapY; tile.y < mapHeight + mapY; tile.y++) {
FreerailsTile tt = (FreerailsTile) w.getTile(tile.x, tile.y);
if (tt.getTrackPiece().equals(NullTrackPiece.getInstance())) {
int typeNumber = tt.getTerrainTypeID();
TerrainType terrainType = (TerrainType) w.get(
SKEY.TERRAIN_TYPES, typeNumber);
one2oneImage.setRGB(tile.x - mapX, tile.y - mapY,
terrainType.getRGB());
} else {
/* black with alpha of 1 */
one2oneImage.setRGB(tile.x - mapX, tile.y - mapY,
0xff000000);
}
}
}
renderOffScreenImage();
}

end_Types

Class: jfreerails.server.parser.CargoAndTerrainHandlerImpl

Documentation

No documentation available

Source Code

public void end_Types() throws SAXException {
// no need to do anything here.
}

Called Methods

No outgoing method calls

removeFromTail

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public TrainPositionOnMap removeFromTail(TrainPositionOnMap b) {
if (tailsAreEqual(this, b)) {
int newLength = this.getLength() - b.getLength() + 2;
int[] newXpoints = new int[newLength];
int[] newYpoints = new int[newLength];
// Copy from this
for (int i = 0; i < newLength - 1; i++) {
newXpoints[i] = this.getX(i);
newYpoints[i] = this.getY(i);
}
// Copy tail from b
newXpoints[newLength - 1] = b.getX(0);
newYpoints[newLength - 1] = b.getY(0);
return new TrainPositionOnMap(newXpoints, newYpoints, speed,
acceleration, activity);
}
throw new IllegalArgumentException();
}

listGet

Class: jfreerails.world.top.NonNullElements

Documentation

No documentation available

Source Code

private FreerailsSerializable listGet(int i) {
if (null == this.skey) {
return w.get(principal, key, i);
}
return w.get(skey, i);
}

itemRemoved

Class: jfreerails.world.top.WorldListListener

Documentation

No documentation available

Source Code

void itemRemoved(KEY key, int index, FreerailsPrincipal principal);

Called Methods

No outgoing method calls

contains

Class: jfreerails.client.common.ImageManagerImpl

Documentation

No documentation available

Source Code

public boolean contains(String relativeFilename) {
relativeFilename = relativeFilename.replace(' ', '_');
if (imageHashMap.containsKey(relativeFilename)) {
return true;
}
File f = new File(pathToWriteTo + File.separator + relativeFilename);
if (f.isFile()) {
return true;
}
return false;
}

Called Methods

No outgoing method calls

generate

Class: jfreerails.move.WorldDiffMove

Documentation

No documentation available

Source Code

public static WorldDiffMove generate(WorldDiffs diffs, Cause cause) {
return new WorldDiffMove(diffs.getUnderlying(), diffs, cause);
}

deltaCash

Class: jfreerails.world.accounts.Receipt

Documentation

No documentation available

Source Code

public Money deltaCash() {
return amount;
}

Called Methods

No outgoing method calls

testCanRemoveFromHead

Class: jfreerails.world.train.TrainPositionOnMapTest

Documentation

No documentation available

Source Code

public void testCanRemoveFromHead() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20, 40, 50 },
new int[] { 11, 22, 44, 55 });
b = TrainPositionOnMap.createInstance(new int[] { 10, 20, 30 },
new int[] { 11, 22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 30, 40, 50 },
new int[] { 33, 44, 55 });
assertTrue(!b.canRemoveFromHead(a));
assertTrue(a.canRemoveFromHead(b));
assertTrue(!c.canRemoveFromHead(b));
assertTrue(!b.canRemoveFromHead(c));
assertTrue(!c.canRemoveFromHead(a));
assertTrue(!a.canRemoveFromHead(c));
}

close

Class: jfreerails.util.FlowRateInputStream

Documentation

No documentation available

Source Code

@Override
public void close() throws IOException {
closeRequested = true;
super.close();
do {
try {
Thread.currentThread();
Thread.sleep(50L);
} catch (InterruptedException interruptedexception) {
}
} while (running);
logger.info(String.valueOf(String.valueOf((new StringBuffer("Stream "))
.append(streamName).append(": Open duration = ").append(
(System.currentTimeMillis() - openTimeMillis) / 1000D)
.append(", Byte received = ").append(totalByteReceived).append(
" (").append((int) (totalByteReceived / 1024D)).append(
" Ko), overall flow rate = ").append(overallRate())
.append(" Ko/s"))));
}

testGeneratePath

Class: jfreerails.controller.TrackPathFinderTest

Documentation

No documentation available

Source Code

public void testGeneratePath() {
try {
BuildTrackStrategy bts = BuildTrackStrategy.getSingleRuleInstance(
0, world);
TrackPathFinder pathFinder = new TrackPathFinder(world, testPlayer
.getPrincipal());
List l = pathFinder.generatePath(new ImPoint(0, 0), new ImPoint(0,
5), bts);
assertEquals(5, l.size());
List list2 = pathFinder.generatePath(new ImPoint(5, 5),
new ImPoint(5, 10), bts);
assertEquals(5, list2.size());
list2 = pathFinder.generatePath(new ImPoint(5, 10), new ImPoint(5,
5), bts);
assertEquals(5, list2.size());
} catch (PathNotFoundException e) {
fail();
}
}

numberOfMapDifferences

Class: jfreerails.world.top.WorldDiffs

Documentation

/** Used by unit tests. */

Source Code

/** Used by unit tests. */
public int numberOfMapDifferences() {
return this.mapDiff.size();
}

Called Methods

No outgoing method calls

setBuildTrackStrategy

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

No documentation available

Source Code

private void setBuildTrackStrategy() {
ArrayList<Integer> ruleIDs = new ArrayList<Integer>();
ruleIDs.add(selectionSet.get(TrackRule.TrackCategories.track));
ruleIDs.add(selectionSet.get(TrackRule.TrackCategories.bridge));
ruleIDs.add(selectionSet.get(TrackRule.TrackCategories.tunnel));
BuildTrackStrategy bts = BuildTrackStrategy.getMultipleRuleInstance(
ruleIDs, modelRoot.getWorld());
modelRoot.setProperty(ModelRoot.Property.BUILD_TRACK_STRATEGY, bts);
}

equals

Class: jfreerails.world.common.ImInts

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImInts))
return false;
final ImInts other = (ImInts) o;
if (!Arrays.equals(ints, other.ints))
return false;
return true;
}

Called Methods

No outgoing method calls

calculateCarLoads

Class: jfreerails.client.renderer.StationBoxRenderer

Documentation

/**
* The length of the returned array is the number of complete carloads of
* the specified cargo category in the specified bundle. The values in the
* array are the type of the cargo. E.g. if the bundle contained 2 carloads
* of cargo type 3 and 1 of type 7, {3, 3, 7} would be returned.
*/

Source Code

/**
* The length of the returned array is the number of complete carloads of
* the specified cargo category in the specified bundle. The values in the
* array are the type of the cargo. E.g. if the bundle contained 2 carloads
* of cargo type 3 and 1 of type 7, {3, 3, 7} would be returned.
*/
private int[][] calculateCarLoads(ImmutableCargoBundle cb) {
int categories = CargoType.getNumberOfCategories();
int numCargoTypes = w.size(SKEY.CARGO_TYPES);
int[] numberOfCarLoads = new int[categories];
int[][] cars = new int[categories][numCargoTypes];
for (int i = 0; i < numCargoTypes; i++) {
CargoType ct = (CargoType) w.get(SKEY.CARGO_TYPES, i);
int carsOfThisCargo = cb.getAmount(i)
/ WagonType.UNITS_OF_CARGO_PER_WAGON;
numberOfCarLoads[ct.getCategory().getNumber()] += carsOfThisCargo;
cars[ct.getCategory().getNumber()][i] += carsOfThisCargo;
}
int[][] returnMatrix = new int[categories][];
for (int category = 0; category < categories; category++) {
int[] returnValue = new int[numberOfCarLoads[category]];
int arrayIndex = 0;
for (int cargoType = 0; cargoType < numCargoTypes; cargoType++) {
for (int j = 0; j < cars[category][cargoType]; j++) {
returnValue[arrayIndex] = cargoType;
arrayIndex++;
}
}
returnMatrix[category] = returnValue;
}
return returnMatrix;
}

doMove

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public MoveStatus doMove(Move m) {
MoveStatus ms = this.moveReceiver.tryDoMove(m);
this.moveReceiver.processMove(m);
return ms;
}

mouseReleased

Class: jfreerails.client.view.MapViewJComponentMouseAdapter

Documentation

No documentation available

Source Code

@Override
public void mouseReleased(MouseEvent evt) {
MapViewJComponentConcrete.this.setCursor(Cursor
.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}

Called Methods

No outgoing method calls

end_CannotBuildOnTheseTerrainTypes

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void end_CannotBuildOnTheseTerrainTypes() throws SAXException {
legalTrackPlacement = new LegalTrackPlacement(terrainTypes,
LegalTrackPlacement.PlacementRule.ANYWHERE_EXCEPT_ON_THESE);
terrainTypes = null;
}

Called Methods

No outgoing method calls

testGetCopy

Class: jfreerails.server.MapFixtureFactory2Test

Documentation

No documentation available

Source Code

public void testGetCopy() {
World w2;
w1 = getCopy();
assertNotNull(w1);
w2 = getCopy();
assertNotNull(w2);
assertNotSame(w1, w2);
assertEquals(w1, w2);
}

getTransactionTimeStamp

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public GameTime getTransactionTimeStamp(FreerailsPrincipal p, int i) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = bankAccounts.get(playerIndex, i);
return tats.getTimeStamp();
}

toString

Class: jfreerails.world.track.FreerailsTile

Documentation

No documentation available

Source Code

@Override
public String toString() {
return "trackPiece=" + trackPiece.toString() + " and terrainType is "
+ terrainType;
}

Called Methods

No outgoing method calls

EchoGameServer

Class: jfreerails.network.EchoGameServer

Documentation

No documentation available

Source Code

private EchoGameServer() {
}

Called Methods

No outgoing method calls

setText

Class: jfreerails.controller.CopyableTextJPanel

Documentation

No documentation available

Source Code

public void setText(String s){
this.jTextArea1.setText(s);
}

Called Methods

No outgoing method calls

selectWagonsActionPerformed

Class: experimental.DialogueBoxTester

Documentation

No documentation available

Source Code

private void selectWagonsActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_selectWagonsActionPerformed
// Add your handling code here:
dialogueBoxController.showSelectWagons();
}// GEN-LAST:event_selectWagonsActionPerformed

newGame

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public void newGame(String mapName) {
newPlayersAllowed = false;
confirmedPlayers.clear();
try {
World world = (World) savedGamesManager.newMap(mapName);
String[] passwords = new String[players.size()];
/* Add players to world. */
for (int i = 0; i < players.size(); i++) {
String name = players.get(i).username;
Player p = new Player(name, i);
Move addPlayerMove = AddPlayerMove.generateMove(world, p);
MoveStatus ms = addPlayerMove.doMove(world, Player.AUTHORITATIVE);
if(!ms.ok) throw new IllegalStateException();
passwords[i] = players.get(i).password;
}
serverGameModel.setWorld(world, passwords);
setServerGameModel(serverGameModel);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendWorldUpdatedCommand();
logger.fine("newGame");
}

nextIterator

Class: jfreerails.controller.ToAndFroPathIterator

Documentation

No documentation available

Source Code

private void nextIterator() {
path = new FreerailsPathIteratorImpl(list, forwards);
}

Called Methods

No outgoing method calls

TrainRendererTest

Class: jfreerails.client.renderer.TrainRendererTest

Documentation

No documentation available

Source Code

public TrainRendererTest() {
}

Called Methods

No outgoing method calls

setCargoOnTrain

Class: jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest

Documentation

No documentation available

Source Code

private void setCargoOnTrain(CargoBatch cb, int amount) {
TrainModel train = (TrainModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.TRAINS,
0);
MutableCargoBundle bundle = new MutableCargoBundle(getCargoOnTrain());
bundle.setAmount(cb, amount);
w.set(MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES, train.getCargoBundleID(), bundle
.toImmutableCargoBundle());
}

setListOfPlayers

Class: jfreerails.launcher.ConnectedPlayersJPanel

Documentation

No documentation available

Source Code

void setListOfPlayers(String[] players) {
jList1.setListData(players);
}

Called Methods

No outgoing method calls

fromMoveStatus

Class: jfreerails.controller.PreMoveStatus

Documentation

No documentation available

Source Code

public static PreMoveStatus fromMoveStatus(MoveStatus ms) {
if (ms.ok) {
return PRE_MOVE_OK;
}
return new PreMoveStatus(ms);
}

Called Methods

No outgoing method calls

toArray

Class: jfreerails.util.IntArray

Documentation

/**
* Constructs and returns a simple array containing the same data as held in
* a portion of this growable array.
*
* @param offset
* start offset in array
* @param length
* number of characters to use
* @return array containing a copy of the data
*/

Source Code

/**
* Constructs and returns a simple array containing the same data as held in
* a portion of this growable array.
*
* @param offset
* start offset in array
* @param length
* number of characters to use
* @return array containing a copy of the data
*/
public int[] toArray(int offset, int length) {
return (int[]) buildArray(int.class, offset, length);
}

setValue

Class: jfreerails.launcher.ProgressJPanel

Documentation

No documentation available

Source Code

public void setValue(int i) {
int value = i * 100 / stepSize;
value += 100 * step;
progressBar.setValue(value);
}

Called Methods

No outgoing method calls

readNextBuffer

Class: jfreerails.util.CompressedInputStream

Documentation

No documentation available

Source Code

private boolean readNextBuffer() throws IOException {
byte compressionFlag = -1;
compressionFlag = (byte) super.in.read();
if (compressionFlag == -1) {
return false;
}
maxReadIndex = super.in.read() & 0xff;
maxReadIndex = maxReadIndex << 8 | super.in.read() & 0xff;
maxReadIndex = maxReadIndex << 8 | super.in.read() & 0xff;
maxReadIndex = maxReadIndex << 8 | super.in.read() & 0xff;
if (buffer.length < maxReadIndex) {
buffer = new byte[maxReadIndex + 40960];
}
if (compressionFlag == 1) {
int compSize = super.in.read() & 0xff;
compSize = compSize << 8 | super.in.read() & 0xff;
compSize = compSize << 8 | super.in.read() & 0xff;
compSize = compSize << 8 | super.in.read() & 0xff;
if (compBuffer.length < compSize) {
compBuffer = new byte[compSize + 40960];
}
for (int read = 0; read < compSize; read += super.in.read(
compBuffer, read, compSize - read)) {
}
inflater.reset();
inflater.setInput(compBuffer, 0, compSize);
try {
inflater.inflate(buffer);
} catch (DataFormatException ex) {
throw new IOException("Data format exception");
}
} else if (compressionFlag == 0) {
for (int read = 0; read < maxReadIndex; read += super.in.read(
buffer, read, maxReadIndex - read)) {
}
}
readIndex = 0;
return true;
}

Called Methods

No outgoing method calls

LoadGameJPanel

Class: jfreerails.client.view.LoadGameJPanel

Documentation

/** Creates new form LoadGameJPanel */

Source Code

/** Creates new form LoadGameJPanel */
public LoadGameJPanel() {
initComponents();
}

FlatTrackExplorer

Class: jfreerails.controller.FlatTrackExplorer

Documentation

No documentation available

Source Code

public FlatTrackExplorer(ReadOnlyWorld world, PositionOnTrack p) {
w = world;
FreerailsTile tile = (FreerailsTile) world.getTile(p.getX(), p.getY());
if (tile.getTrackPiece().getTrackTypeID() == NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
throw new IllegalArgumentException(p.toString());
}
this.currentPosition = PositionOnTrack.createComingFrom(p.getX(), p
.getY(), p.cameFrom());
}

NearestStationFinder

Class: jfreerails.client.view.NearestStationFinder

Documentation

No documentation available

Source Code

public NearestStationFinder(ReadOnlyWorld w, FreerailsPrincipal player) {
world = w;
this.principal = player;
}

Called Methods

No outgoing method calls

RenderersRootImpl

Class: jfreerails.client.top.RenderersRootImpl

Documentation

No documentation available

Source Code

public RenderersRootImpl(ReadOnlyWorld w, FreerailsProgressMonitor pm)
throws IOException {
URL out = RenderersRootImpl.class.getResource("/experimental");
imageManager = new ImageManagerImpl("/jfreerails/client/graphics/", out
.getPath());
tiles = loadNewTileViewList(w, pm);
trackPieceViewList = loadTrackViews(w, pm);
//rr = new OldTrainImages(w, imageManager, pm);
loadTrainImages(w, pm);
preloadSounds(pm);
}

toImmutableSchedule

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public ImmutableSchedule toImmutableSchedule() {
TrainOrdersModel[] ordersArray = new TrainOrdersModel[orders.size()];
for (int i = 0; i < ordersArray.length; i++) {
ordersArray[i] = orders.get(i);
}
return new ImmutableSchedule(ordersArray, this.nextScheduledOrder,
this.hasPriorityOrders);
}

Called Methods

No outgoing method calls

calcOffSet

Class: jfreerails.world.train.TrainMotion

Documentation

No documentation available

Source Code

private double calcOffSet(double t) {
double offset = getDistance(t) + initialPosition - trainLength;
return offset;
}

hashCode

Class: jfreerails.world.train.ConstAcc

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
long temp;
temp = u != +0.0d ? Double.doubleToLongBits(u) : 0l;
result = (int) (temp ^ (temp >>> 32));
temp = a != +0.0d ? Double.doubleToLongBits(a) : 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
temp = finalT != +0.0d ? Double.doubleToLongBits(finalT) : 0l;
result = 29 * result + (int) (temp ^ (temp >>> 32));
return result;
}

Called Methods

No outgoing method calls

cargoBatchIterator

Class: jfreerails.world.cargo.MutableCargoBundle

Documentation

/**
* Note, calling hasNext() or next() on the returned iterator throws a
* ConcurrentModificationException if this CargoBundle has changed since the
* iterator was acquired.
*/

Source Code

/**
* Note, calling hasNext() or next() on the returned iterator throws a
* ConcurrentModificationException if this CargoBundle has changed since the
* iterator was acquired.
*/
public Iterator<CargoBatch> cargoBatchIterator() {
final Iterator<CargoBatch> it = sortedMap.keySet().iterator();
/*
* A ConcurrentModificationException used to get thrown when the amount
* of cargo was set to 0, since this resulted in the key being removed
* from the hashmap. The iterator below throws a
* ConcurrentModificationException whenever this CargoBundle has been
* changed since the iterator was acquired. This should mean that if the
* cargo bundle gets changed while the iterator is in use, you will know
* about it straight away.
*/
return new Iterator<CargoBatch>() {
final int updateIDAtCreation = updateID;
public boolean hasNext() {
if (updateIDAtCreation != updateID) {
throw new ConcurrentModificationException();
}
return it.hasNext();
}
public CargoBatch next() {
if (updateIDAtCreation != updateID) {
throw new ConcurrentModificationException();
}
return it.next();
}
public void remove() {
throw new UnsupportedOperationException(
"Use CargoBundle.setAmount(CargoBatch cb, 0)");
}
};
}

Called Methods

No outgoing method calls

addMainMapAndOverviewMapMediatorIfNecessary

Class: experimental.SimpleComponentFactoryImpl2

Documentation

No documentation available

Source Code

private void addMainMapAndOverviewMapMediatorIfNecessary() {
if (this.mainMap != null && this.overviewMap != null
&& null == this.mediator) {
// Rectangle r = this.overviewMap.getMainMapVisibleRect();
this.mediator = new MainMapAndOverviewMapMediator(overviewMap,
mainMapScrollPane1.getViewport(), mainMap, r);
}
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.controller.MoveTrainPreMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof MoveTrainPreMove))
return false;
final MoveTrainPreMove moveTrainPreMove = (MoveTrainPreMove) o;
if (trainID != moveTrainPreMove.trainID)
return false;
if (!principal.equals(moveTrainPreMove.principal))
return false;
return true;
}

Called Methods

No outgoing method calls

canBuildOnThisTerrain

Class: jfreerails.world.track.LegalTrackPlacement

Documentation

No documentation available

Source Code

public boolean canBuildOnThisTerrain(TerrainType.Category terrainType) {
if (PlacementRule.ONLY_ON_THESE == placementRule) {
return terrainTypes.contains(terrainType);
}
return !terrainTypes.contains(terrainType);
}

updateTrainPosition

Class: experimental.TrainMotionExpt

Documentation

No documentation available

Source Code

private void updateTrainPosition() {
Random rand = new Random(System.currentTimeMillis());
MoveTrainPreMove moveTrain = new MoveTrainPreMove(0, principal);
Move m;
if (rand.nextInt(10) == 0) {
m = moveTrain.stopTrain(world);
} else {
m = moveTrain.generateMove(world);
}
MoveStatus ms = m.doMove(world, principal);
if (!ms.ok)
throw new IllegalStateException(ms.message);
ActivityIterator ai = world.getActivities(principal, 0);
while (ai.hasNext()) {
ai.nextActivity();
finishTime = ai.getFinishTime();
}
}

testUtilityCalculation

Class: jfreerails.server.CityEconomicModelTest

Documentation

/** Tests calculating the utility of a City. */

Source Code

/** Tests calculating the utility of a City. */
public void testUtilityCalculation() {
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.network.specifics.LoadGameMessage2Server

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = id;
result = 29 * result + filename.hashCode();
return result;
}

Called Methods

No outgoing method calls

drawTrackPieceIcon

Class: jfreerails.client.renderer.TrackPieceRenderer

Documentation

No documentation available

Source Code

void drawTrackPieceIcon(int trackTemplate, java.awt.Graphics g, int x,
int y, java.awt.Dimension tileSize);

Called Methods

No outgoing method calls

initTarget

Class: jfreerails.server.TrainUpdater

Documentation

/**
* @return a move that initialises the trains schedule.
*/

Source Code

/**
* @return a move that initialises the trains schedule.
*/
public static Move initTarget(TrainModel train, int trainID,
ImmutableSchedule currentSchedule, FreerailsPrincipal principal) {
Vector<Move> moves = new Vector<Move>();
int scheduleID = train.getScheduleID();
MutableSchedule schedule = new MutableSchedule(currentSchedule);
ImInts wagonsToAdd = schedule.getWagonsToAdd();
if (null != wagonsToAdd) {
int engine = train.getEngineType();
ChangeTrainMove move = ChangeTrainMove.generateMove(trainID, train,
engine, wagonsToAdd, principal);
moves.add(move);
}
schedule.gotoNextStation();
ImmutableSchedule newSchedule = schedule.toImmutableSchedule();
ChangeTrainScheduleMove move = new ChangeTrainScheduleMove(scheduleID,
currentSchedule, newSchedule, principal);
moves.add(move);
return new CompositeMove(moves.toArray(new Move[1]));
}

calculations

Class: jfreerails.controller.CalcCargoSupplyRateAtStation

Documentation

/**
*
* Process each existing station, updating what is supplied to it.
*
* @param station
* A StationModel object to be processed
*
*/

Source Code

/**
*
* Process each existing station, updating what is supplied to it.
*
* @param station
* A StationModel object to be processed
*
*/
public StationModel calculations(StationModel station) {
int[] cargoSupplied = new int[w.size(SKEY.CARGO_TYPES)];
Vector<CargoElementObject> supply = scanAdjacentTiles();
// grab the supply rates from the vector
for (int i = 0; i < supply.size(); i++) {
cargoSupplied[i] = supply.get(i).getRate();
}
// set the supply rates for the current station
SupplyAtStation supplyAtStation = new SupplyAtStation(cargoSupplied);
station = new StationModel(station, supplyAtStation);
station = new StationModel(station, getDemand());
station = new StationModel(station, getConversion());
return station;
}

CompanyDetails

Class: jfreerails.client.view.CompanyDetails

Documentation

No documentation available

Source Code

CompanyDetails(String n, Color c) {
color = c;
name = n;
for (int i = 0; i < 100; i++) {
value[i] = Integer.MIN_VALUE;
}
}

Called Methods

No outgoing method calls

addD3

Class: jfreerails.util.List3D

Documentation

No documentation available

Source Code

int addD3(int d1, int d2, T element);

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.util.List2DImpl

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return sizeD1();
}

getStockInRRs

Class: jfreerails.controller.FinancialDataGatherer

Documentation

No documentation available

Source Code

public int[] getStockInRRs() {
return stockInRRs;
}

Called Methods

No outgoing method calls

testMove

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

public void testMove(){}

Called Methods

No outgoing method calls

testGet

Class: jfreerails.world.top.WorldImplTest

Documentation

No documentation available

Source Code

public void testGet() {
WorldImpl w = new WorldImpl();
w.add(SKEY.TERRAIN_TYPES, fs);
assertEquals(w.get(SKEY.TERRAIN_TYPES, 0), fs);
}

getSchedule

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private MutableSchedule getSchedule() {
FreerailsPrincipal principal = modelRoot.getPrincipal();
ReadOnlyWorld w = modelRoot.getWorld();
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
trainNumber);
ImmutableSchedule immutableSchedule = (ImmutableSchedule) w.get(
principal, KEY.TRAIN_SCHEDULES, train.getScheduleID());
return new MutableSchedule(immutableSchedule);
}

updateGameTime

Class: jfreerails.server.ServerGameModelImpl

Documentation

No documentation available

Source Code

private void updateGameTime() {
moveExecuter.processMove(TimeTickMove.getMove(world));
}

JFrameMinimumSizeEnforcer

Class: jfreerails.controller.JFrameMinimumSizeEnforcer

Documentation

No documentation available

Source Code

public JFrameMinimumSizeEnforcer(int w, int h) {
this.minHeight = h;
this.minWidth = w;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.track.TrackConfiguration

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final TrackConfiguration that = (TrackConfiguration) o;
if (configuration != that.configuration)
return false;
return true;
}

Called Methods

No outgoing method calls

getRGBvalue

Class: jfreerails.world.track.TrackRuleProperties

Documentation

No documentation available

Source Code

private int getRGBvalue() {
return rGBvalue;
}

Called Methods

No outgoing method calls

paint

Class: jfreerails.client.view.OverHeadTrainView

Documentation

No documentation available

Source Code

public void paint(Graphics2D g) {
g.setColor(Color.BLUE);
g.setStroke(new BasicStroke(10));
Double time = (Double)mr.getProperty(Property.TIME);
for (int k = 0; k < w.getNumberOfPlayers(); k++) {
FreerailsPrincipal principal = w.getPlayer(k).getPrincipal();
int selectedTrain = -1;
if (mr.getPrincipal().getWorldIndex() == principal.getWorldIndex()) {
//These are our trains...
Object property = mr.getProperty(Property.SELECTED_TRAIN);
if (null != property) {
selectedTrain = (Integer) property;
}
}
for (int i = 0; i < w.size(principal, KEY.TRAINS); i++) {
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS, i);
// TrainPositionOnMap pos = (TrainPositionOnMap) w.get(
// principal, KEY.TRAIN_POSITIONS, i);
TrainAccessor ta = new TrainAccessor(w, principal, i);
TrainPositionOnMap pos = ta.findPosition(time);
if (pos.isCrashSite()
&& (pos.getFrameCt() <= TrainPositionOnMap.CRASH_FRAMES_COUNT)) {
trainRenderer.paintTrainCrash(g, pos);
if (pos.getFrameCt() == 1) {
try {
soundManager.playSound(
"/jfreerails/client/sounds/traincrash.wav",
1);
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
TrainImages.Highlight highlight = i == selectedTrain ? TrainImages.Highlight.SELECTED: null;
trainRenderer.paintTrain(g, train, pos, highlight);
}
}
}
}

getScreenMode

Class: jfreerails.launcher.ClientOptionsJPanel

Documentation

No documentation available

Source Code

int getScreenMode() {
if (this.fullScreenButton.isSelected()) {
return ScreenHandler.FULL_SCREEN;
} else if (this.windowedButton.isSelected()) {
return ScreenHandler.WINDOWED_MODE;
} else if (this.fixedSizeButton.isSelected()) {
return ScreenHandler.FIXED_SIZE_WINDOWED_MODE;
} else {
throw new IllegalStateException();
}
}

Called Methods

No outgoing method calls

testUpgradeTrack

Class: jfreerails.client.renderer.BuildTrackControllerTest

Documentation

No documentation available

Source Code

public void testUpgradeTrack() {
// Build the track.
testBuildTrack();
// Change the strategy.
BuildTrackStrategy bts = BuildTrackStrategy.getSingleRuleInstance(
doubleTrackRuleID, modelRoot.getWorld());
trackBuilder.setBuildTrackStrategy(bts);
trackBuilder.setTrackBuilderMode(BuildMode.UPGRADE_TRACK);
// Upgrade part of the track.
modelRoot.setProperty(Property.CURSOR_POSITION, new ImPoint(15, 10));
buildTrackController
.setProposedTrack(new ImPoint(20, 10), trackBuilder);
buildTrackController.updateUntilComplete();
assertTrue(buildTrackController.isBuildTrackSuccessful());
buildTrackController.updateWorld(trackBuilder);
FreerailsTile tile = (FreerailsTile) w.getTile(10, 10);
assertEquals(singleTrackRuleID, tile.getTrackPiece().getTrackTypeID());
tile = (FreerailsTile) w.getTile(15, 10);
assertEquals(doubleTrackRuleID, tile.getTrackPiece().getTrackTypeID());
tile = (FreerailsTile) w.getTile(17, 10);
assertEquals(doubleTrackRuleID, tile.getTrackPiece().getTrackTypeID());
tile = (FreerailsTile) w.getTile(20, 10);
assertEquals(doubleTrackRuleID, tile.getTrackPiece().getTrackTypeID());
}

getListDiffs

Class: jfreerails.world.top.WorldDiffs

Documentation

No documentation available

Source Code

public Iterator<ListKey> getListDiffs() {
return listDiff.keySet().iterator();
}

Called Methods

No outgoing method calls

getS

Class: jfreerails.world.train.SpeedAgainstTime

Documentation

/**
* @return The distance traveled during at time given by getT().
*/

Source Code

/**
* @return The distance traveled during at time given by getT().
*/
double getS();

Called Methods

No outgoing method calls

writeImage

Class: jfreerails.client.common.ImageManagerImpl

Documentation

No documentation available

Source Code

public void writeImage(String relativeFilename) throws IOException {
if (null == pathToWriteTo)
throw new NullPointerException("null == pathToWriteTo");
relativeFilename = relativeFilename.replace(' ', '_');
File f = new File(pathToWriteTo + File.separator + relativeFilename);
if (imageHashMap.containsKey(relativeFilename)) {
RenderedImage i = (RenderedImage) imageHashMap
.get(relativeFilename);
String pathName = f.getPath();
File path = new File(pathName);
path.mkdirs();
ImageIO.write(i, "png", f);
logger.info("Writing " + f);
} else {
throw new NoSuchElementException(relativeFilename);
}
}

Called Methods

No outgoing method calls

getName

Class: jfreerails.controller.VerifyStationName

Documentation

No documentation available

Source Code

public String getName() {
String appropriateName = nameToVerify;
boolean found = false;
String tempName = null;
// if (w.size(KEY.STATIONS) <= 0) {
// //if there are no stations, then obviously the name isn't taken
// return appropriateName;
// }
found = checkStationExists(appropriateName);
if (!found) {
return appropriateName;
}
// a station with that name already exists, so we need to find another
// name
for (int i = 0; i < stationAlternatives.size(); i++) {
tempName = appropriateName + " " + stationAlternatives.elementAt(i);
found = checkStationExists(tempName);
if (!found) {
return tempName;
}
}
int j = 7; // for number of names that have already been used
while (found) {
j++;
tempName = appropriateName + "Station #" + j;
found = checkStationExists(tempName);
}
return tempName;
}

end_ListOfLegalRoutesAcrossNode

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* A container element end event handling method.
*/

Source Code

/**
* A container element end event handling method.
*/
void end_ListOfLegalRoutesAcrossNode() throws SAXException;

Called Methods

No outgoing method calls

getWorld

Class: jfreerails.controller.SimpleMoveExecutor

Documentation

No documentation available

Source Code

public ReadOnlyWorld getWorld() {
return w;
}

Called Methods

No outgoing method calls

jList1KeyPressed

Class: jfreerails.client.view.TrainListJPanel

Documentation

No documentation available

Source Code

private void jList1KeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_jList1KeyPressed
// Add your handling code here:
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
showTrainDetails.actionPerformed(null);
}
}// GEN-LAST:event_jList1KeyPressed

Called Methods

No outgoing method calls

addSplitMoveReceiver

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public void addSplitMoveReceiver(MoveReceiver l) {
this.moveFork.addSplitMoveReceiver(l);
}

addTile

Class: jfreerails.server.CityEconomicModel

Documentation

No documentation available

Source Code

void addTile(TerrainType type) {
Random rand = new Random();
// Pick a spot at random at which to place the tile.
if (clearTiles.size() > 0) {
int tilePos = rand.nextInt(clearTiles.size());
Point p = clearTiles.remove(tilePos);
if (type.getCategory().equals(TerrainType.Category.Urban)) {
urbanTiles.add(new Tile(p, type));
} else if (type.getCategory().equals(TerrainType.Category.Industry)) {
industryTiles.add(new Tile(p, type));
industriesNotAtCity.remove(type);
} else if (type.getCategory().equals(TerrainType.Category.Country)) {
throw new IllegalArgumentException(
"call remove(.) to replace a city tile with a country tile!");
} else if (type.getCategory().equals(TerrainType.Category.Resource)) {
resourceTiles.add(new Tile(p, type));
}
}
}

move

Class: jfreerails.world.common.PositionOnTrack

Documentation

No documentation available

Source Code

public void move(Step step) {
this.x += step.deltaX;
this.y += step.deltaY;
this.cameFrom = step.getOpposite();
}

testRemove

Class: jfreerails.util.ListXDTest

Documentation

No documentation available

Source Code

public void testRemove(){
Integer i = new Integer(4);
list2d.addD2(4, i);
try{
list2d.removeLastD1();
fail();
}catch (Exception e) {
//An exception should be thrown since the list we are trying to remove is not empty.
}
list3d.addD3(2,1,i);
//We now should be able to remove the last
try{
list3d.removeLastD1();
fail();
}catch (Exception e) {
//An exception should be thrown since the list we are trying to remove is not empty.
}
try{
list3d.removeLastD2(3);
fail();
}catch (Exception e) {
//An exception should be thrown since the list we are trying to remove is not empty.
}
}

testDefensiveCopy

Class: jfreerails.world.top.WorldImplTest

Documentation

/**
* Tests that changing the object returned by defensiveCopy() does not alter
* the world object that was copied.
*/

Source Code

/**
* Tests that changing the object returned by defensiveCopy() does not alter
* the world object that was copied.
*/
public void testDefensiveCopy() {
World original;
World copy;
original = new WorldImpl();
copy = original.defensiveCopy();
assertNotSame("The copies should be different objects.", original, copy);
assertEquals("The copies should be logically equal.", original, copy);
copy.add(SKEY.TERRAIN_TYPES, fs);
assertFalse(original.equals(copy));
assertFalse(copy.equals(original));
assertEquals(1, copy.size(SKEY.TERRAIN_TYPES));
assertEquals(0, original.size(SKEY.TERRAIN_TYPES));
}

getTrackPieceViewList

Class: jfreerails.client.top.RenderersRootImpl

Documentation

No documentation available

Source Code

public TrackPieceRendererList getTrackPieceViewList() {
return this.trackPieceViewList;
}

Called Methods

No outgoing method calls

componentHidden

Class: jfreerails.controller.JFrameMinimumSizeEnforcer

Documentation

No documentation available

Source Code

public void componentHidden(ComponentEvent arg0) {
}

Called Methods

No outgoing method calls

setCursorLocation

Class: jfreerails.client.top.BuildIndustryJPopupMenu

Documentation

No documentation available

Source Code

public void setCursorLocation(Point p) {
cursorLocation.x = p.x;
cursorLocation.y = p.y;
}

Called Methods

No outgoing method calls

writeImage

Class: jfreerails.client.common.ImageManager

Documentation

No documentation available

Source Code

void writeImage(String relativeFilename) throws IOException;

Called Methods

No outgoing method calls

SelectWagonsJPanel

Class: jfreerails.client.view.SelectWagonsJPanel

Documentation

No documentation available

Source Code

public SelectWagonsJPanel() {
initComponents();
updateMaxWagonsText();
URL url = SelectWagonsJPanel.class
.getResource("/jfreerails/data/station.gif");
Image tempImage = (new javax.swing.ImageIcon(url)).getImage();
stationView = defaultConfiguration.createCompatibleImage(tempImage
.getWidth(null), tempImage.getHeight(null),
Transparency.BITMASK);
Graphics g = stationView.getGraphics();
g.drawImage(tempImage, 0, 0, null);
}

ConnectedPlayersJPanel

Class: jfreerails.launcher.ConnectedPlayersJPanel

Documentation

/** Creates new form ConnectedPlayersJPanel */

Source Code

/** Creates new form ConnectedPlayersJPanel */
public ConnectedPlayersJPanel() {
initComponents();
}

getLength

Class: jfreerails.world.common.Step

Documentation

/**
* @return the length of this vector. Each tile is 100 units x 100 units.
*/

Source Code

/**
* @return the length of this vector. Each tile is 100 units x 100 units.
*/
public double getLength() {
return length;
}

Called Methods

No outgoing method calls

getMapCursor

Class: jfreerails.client.view.MapViewJComponentConcrete

Documentation

No documentation available

Source Code

public FreerailsCursor getMapCursor() {
return mapCursor;
}

Called Methods

No outgoing method calls

testMove

Class: jfreerails.move.RemoveCargoBundleMoveTest

Documentation

No documentation available

Source Code

@Override
public void testMove() {
MutableCargoBundle bundleA;
MutableCargoBundle bundleB;
bundleA = new MutableCargoBundle();
bundleB = new MutableCargoBundle();
bundleA.setAmount(new CargoBatch(1, 2, 3, 4, 0), 5);
bundleB.setAmount(new CargoBatch(1, 2, 3, 4, 0), 5);
assertEquals(bundleA, bundleB);
Move m = new RemoveCargoBundleMove(0, bundleB.toImmutableCargoBundle(),
MapFixtureFactory.TEST_PRINCIPAL);
assertSurvivesSerialisation(m);
assertTryMoveFails(m);
assertTryUndoMoveFails(m);
getWorld().add(MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES,
bundleA.toImmutableCargoBundle());
assertTryMoveIsOk(m);
assertOkButNotRepeatable(m);
}

generatePath

Class: jfreerails.controller.TrackPathFinder

Documentation

No documentation available

Source Code

public List generatePath(ImPoint start, ImPoint targetPoint,
BuildTrackStrategy bts) throws PathNotFoundException {
setupSearch(start, targetPoint, bts);
pathFinder.search(-1);
IntArray path = pathFinder.retrievePath();
List proposedTrack = convertPath2Points(path);
return proposedTrack;
}

paint

Class: jfreerails.client.renderer.CityNamesRenderer

Documentation

No documentation available

Source Code

public void paint(Graphics2D g) {
g.setColor(Color.WHITE);
g.setFont(new Font("Arial", 0, 20));
// draw city names onto map
for (int i = 0; i < w.size(SKEY.CITIES); i++) {
CityModel tempCity = (CityModel) w.get(SKEY.CITIES, i);
g.drawString(tempCity.getCityName(), tempCity.getCityX() * 30,
tempCity.getCityY() * 30 + 10);
}
}

TrainPositionOnMapTest

Class: jfreerails.world.train.TrainPositionOnMapTest

Documentation

No documentation available

Source Code

public TrainPositionOnMapTest(String arg0) {
super(arg0);
}

Called Methods

No outgoing method calls

setServerGameModel

Class: jfreerails.launcher.Launcher

Documentation

No documentation available

Source Code

private void setServerGameModel() throws IOException {
ClientOptionsJPanel cop = (ClientOptionsJPanel) wizardPages[2];
if (isNewGame()) {
SelectMapJPanel msp2 = (SelectMapJPanel) wizardPages[1];
server.newGame(msp2.getNewMapName());
cop.limitPlayerNames(null);
} else {
// Do nothing since the server is already set up.
}
}

get

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

/**
* Returns the element mapped to the specified item.
*/

Source Code

/**
* Returns the element mapped to the specified item.
*/
FreerailsSerializable get(ITEM item);

Called Methods

No outgoing method calls

setProposedTrack

Class: jfreerails.client.renderer.BuildTrackController

Documentation

/** Sets the proposed track: from the current cursor position to the specified point.*/

Source Code

/** Sets the proposed track: from the current cursor position to the specified point.*/
public void setProposedTrack(ImPoint to,
TrackMoveProducer trackBuilder) {
ImPoint from = getCursorPosition();
assert (trackBuilder.getTrackBuilderMode() != IGNORE_TRACK);
assert (trackBuilder.getTrackBuilderMode() != BUILD_STATION);
buildNewTrack = trackBuilder.getTrackBuilderMode() == BUILD_TRACK;
/*
* If we have just found the route between the two points, don't waste
* time doing it again.
*/
if (null != targetPoint && null != startPoint
&& targetPoint.equals(to)
&& startPoint.equals(from)
&& searchStatus() != IncrementalPathFinder.SEARCH_NOT_STARTED) {
return;
}
worldDiffs.reset();
builtTrack.clear();
isBuildTrackSuccessful = false;
if (from.equals(to)) {
hide();
return;
}
/* Check both points are on the map. */
if (!realWorld.boundsContain(from.x, from.y)
|| !realWorld.boundsContain(to.x, to.y)) {
hide();
return;
}
setTargetPoint(to);
startPoint = from;
try {
BuildTrackStrategy bts = getBts();
if (buildNewTrack) {
path4newTrackFinder.setupSearch(from, to, bts);
} else {
pathOnExistingTrackFinder.setupSearch(from, to);
}
} catch (PathNotFoundException e) {
setCursorMessage(e.getMessage());
return;
}
updateSearch();
}

gotoLastActivity

Class: jfreerails.world.top.ActivityIteratorImpl

Documentation

No documentation available

Source Code

public void gotoLastActivity() {
activityIndex = size - 1;
ant = currentList.get(activityIndex);
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.track.FreerailsTile

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = (trackPiece != null ? trackPiece.hashCode() : 0);
result = 29 * result + terrainType;
return result;
}

Called Methods

No outgoing method calls

AddCargoBundleMove

Class: jfreerails.move.AddCargoBundleMove

Documentation

No documentation available

Source Code

public AddCargoBundleMove(int i, ImmutableCargoBundle item,
FreerailsPrincipal p) {
super(KEY.CARGO_BUNDLES, i, item, p);
}

getUnderlyingList

Class: jfreerails.util.List2DDiff

Documentation

No documentation available

Source Code

@Override
Object getUnderlyingList() {
return underlyingList;
}

Called Methods

No outgoing method calls

loadText

Class: jfreerails.client.view.HtmlJPanel

Documentation

/** Load the help text from file. */

Source Code

/** Load the help text from file. */
String loadText(final URL htmlUrl) {
try {
InputStream in = htmlUrl.openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(
new DataInputStream(in)));
String line;
String text = "";
while ((line = br.readLine()) != null) {
text = text + line;
}
return text;
} catch (Exception e) {
e.printStackTrace();
logger.warning(htmlUrl.toString());
return "Couldn't read: " + htmlUrl;
}
}

Called Methods

No outgoing method calls

createBuildMenu

Class: jfreerails.client.top.GUIComponentFactoryTestImpl

Documentation

No documentation available

Source Code

public JMenu createBuildMenu() {
return buildMenu;
}

Called Methods

No outgoing method calls

NetWorthGraphJPanel

Class: jfreerails.client.view.NetWorthGraphJPanel

Documentation

/**
* This method initializes
*
*/

Source Code

/**
* This method initializes
*
*/
public NetWorthGraphJPanel() {
super();
FONT = new java.awt.Font("Bookman Old Style", java.awt.Font.BOLD, 10);
initialize();
// companies.add(new CompanyDetails("Player 1", Color.BLUE));
// companies.add(new CompanyDetails("Player 2", Color.GREEN));
// companies.add(new CompanyDetails("Player 3", Color.CYAN));
// for(int i = 0; i < companies.size(); i++){
// CompanyDetails cd = (CompanyDetails)companies.get(i);
// cd.fillWithRnadomData();
// }
//
// setAppropriateScale();
}

getPosition

Class: jfreerails.controller.BuildTrackExplorer

Documentation

No documentation available

Source Code

public int getPosition() {
return currentPosition.toInt();
}

sharesHeldByPublic

Class: jfreerails.controller.FinancialDataGatherer

Documentation

No documentation available

Source Code

public int sharesHeldByPublic(){
int[]stock = getStockInThisRRs();
int returnValue = this.totalShares;
for (int i = 0; i < stock.length; i++) {
returnValue -= stock[i];
}
return returnValue;
}

compare

Class: experimental.DistanceComparator

Documentation

No documentation available

Source Code

@Override
public int compare(CityModel a, CityModel b) {
return distSquared(a) - distSquared(b);
}

Called Methods

  • experimental.ConnectAllCities.DistanceComparator.distSquared (external)

AddTransactionMove

Class: jfreerails.move.AddTransactionMove

Documentation

No documentation available

Source Code

public AddTransactionMove(FreerailsPrincipal account, Transaction t,
boolean constrain) {
principal = account;
transaction = t;
constrained = constrain;
if (null == t) {
throw new NullPointerException();
}
}

Called Methods

No outgoing method calls

generateMove

Class: jfreerails.controller.DropOffAndPickupCargoMoveGenerator

Documentation

No documentation available

Source Code

public Move generateMove() {
// The methods that calculate the before and after bundles could be
// called from here.
ChangeCargoBundleMove changeAtStation = new ChangeCargoBundleMove(stationBefore
.toImmutableCargoBundle(), stationAfter.toImmutableCargoBundle(), stationBundleId,
principal);
ChangeCargoBundleMove changeOnTrain = new ChangeCargoBundleMove(trainBefore
.toImmutableCargoBundle(), trainAfter.toImmutableCargoBundle(), trainBundleId,
principal);
moves.add(TransferCargoAtStationMove.CHANGE_AT_STATION_INDEX, changeAtStation);
moves.add(TransferCargoAtStationMove.CHANGE_ON_TRAIN_INDEX, changeOnTrain);
if (autoConsist) {
int engine = train.getTrain().getEngineType();
Move m = ChangeTrainMove.generateMove(this.trainId, train.getTrain(), engine, consist, principal);
moves.add(m);
} else if (waitingForFullLoad) {
// Only generate a move if there is some cargo to add..
if (changeOnTrain.beforeEqualsAfter())
return null;
}
TransferCargoAtStationMove move = new TransferCargoAtStationMove(moves, waitingForFullLoad);
assert move.getChangeAtStation() == changeAtStation;
assert move.getChangeOnTrain() == changeOnTrain;
return move;
}

toString

Class: jfreerails.world.common.GameSpeed

Documentation

No documentation available

Source Code

@Override
public String toString() {
return "GameSpeed:" + String.valueOf(speed);
}

Called Methods

No outgoing method calls

refreshAll

Class: jfreerails.client.renderer.BufferedTiledBackgroundRenderer

Documentation

No documentation available

Source Code

public void refreshAll() {
refreshBackground();
}

getWorld

Class: jfreerails.server.ServerGameModelImpl

Documentation

No documentation available

Source Code

public World getWorld() {
return world;
}

Called Methods

No outgoing method calls

AbstractMoveTestCase

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

protected AbstractMoveTestCase() {
}

Called Methods

No outgoing method calls

getAllClassNames

Class: jfreerails.util.ClassPath

Documentation

No documentation available

Source Code

public List getAllClassNames() {
String path = null;
pathElementsThatHaveAlreadyBeenProcessed = new LinkedList<String>();
jarsThatHAveAlreadyBeenProcessed = new LinkedList<File>();
LinkedList<String> pendingClassPathElements = new LinkedList<String>();
LinkedList<String> processedClassPathElements = new LinkedList<String>();
try {
path = System.getProperty("java.class.path");
} catch (Exception x) {
x.printStackTrace();
}
logger.info("scanning classpath: " + path);
StringTokenizer toke = new StringTokenizer(path, File.pathSeparator);
while (toke.hasMoreTokens()) {
String pathElement = toke.nextToken();
pendingClassPathElements.add(pathElement);
}
for (Iterator<String> iter = pendingClassPathElements.iterator(); iter
.hasNext();) {
String pathElement = iter.next();
LinkedList<String> processPendingElement = processPendingElement(pathElement);
processedClassPathElements.addAll(processPendingElement);
}
return processedClassPathElements;
}

tryMapChanges

Class: jfreerails.move.WorldDiffMove

Documentation

No documentation available

Source Code

private MoveStatus tryMapChanges(World world, boolean undo) {
for (int i = 0; i < diffs.size(); i++) {
MapDiff diff = diffs.get(i);
FreerailsSerializable actual = world.getTile(diff.x, diff.y);
FreerailsSerializable expected = undo ? diff.after : diff.before;
if (!actual.equals(expected)) {
return MoveStatus.moveFailed("expected =" + expected
+ ", actual = " + actual);
}
}
return MoveStatus.MOVE_OK;
}

getSelectedItem

Class: jfreerails.client.view.DisplayModesComboBoxModels

Documentation

No documentation available

Source Code

public Object getSelectedItem() {
return selection;
}

Called Methods

No outgoing method calls

ordersKeyPressed

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void ordersKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_ordersKeyPressed
switch (evt.getKeyCode()) {
case KeyEvent.VK_O: {
// Add priority orders
priorityOrdersJButtonActionPerformed(null);
break;
}
case KeyEvent.VK_N: {
// Add station
addStationJButtonActionPerformed(null);
break;
}
default: {
// do nothing.
}
}
int orderNumber = this.orders.getSelectedIndex();
if (orderNumber == -1) {
// No order is selected.
return;
}
switch (evt.getKeyCode()) {
case KeyEvent.VK_G: {
// Goto station.
gotoStationJMenuItemActionPerformed(null);
break;
}
case KeyEvent.VK_S: {
// Change station
showSelectStation(this.getSchedule(), orderNumber);
break;
}
case KeyEvent.VK_A: {
// Auto schedule
setAutoConsist();
break;
}
case KeyEvent.VK_C: {
// Change add wagon
break;
}
case KeyEvent.VK_DELETE: {
// Remove station
removeStationJMenuItemActionPerformed(null);
break;
}
case KeyEvent.VK_BACK_SPACE: {
// Remove last wagon
removeLastWagon();
break;
}
case KeyEvent.VK_W: {
// toggle wait until full
MutableSchedule s = getSchedule();
TrainOrdersModel order = s.getOrder(orderNumber);
setWaitUntilFull(!order.waitUntilFull);
break;
}
default: {
// do nothing.
}
}
listModel.fireRefresh();
}// GEN-LAST:event_ordersKeyPressed

getActions

Class: jfreerails.client.common.ActionAdapter

Documentation

/**
* @return an enumeration of Action
*/

Source Code

/**
* @return an enumeration of Action
*/
public Enumeration<Action> getActions() {
return new Enumeration<Action>() {
private int i = 0;
public boolean hasMoreElements() {
return (i < actions.length);
}
public Action nextElement() {
return actions[i++];
}
};
}

Called Methods

No outgoing method calls

setNewPlayersAllowed

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public void setNewPlayersAllowed(boolean newPlayersAllowed) {
this.newPlayersAllowed = newPlayersAllowed;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.track.TrackPieceImpl

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
final TrackPieceImpl that = (TrackPieceImpl) o;
if (ownerID != that.ownerID)
return false;
if (ruleNumber != that.ruleNumber)
return false;
if (!configuration.equals(that.configuration))
return false;
if (!trackType.equals(that.trackType))
return false;
return true;
}

StationRadiusRenderer

Class: jfreerails.client.renderer.StationRadiusRenderer

Documentation

No documentation available

Source Code

public StationRadiusRenderer(ModelRoot mr) {
this.modelRoot = mr;
}

Called Methods

No outgoing method calls

setCursorPosition

Class: jfreerails.client.top.UserInputOnMapController

Documentation

No documentation available

Source Code

private void setCursorPosition(ImPoint p) {
// Make a defensive copy.
ImPoint point = p;
modelRoot.setProperty(Property.CURSOR_POSITION, point);
}

hashCode

Class: jfreerails.network.specifics.RefreshListOfGamesMessage2Server

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + id;
return result;
}

Called Methods

No outgoing method calls

getVertexConnectedByEdge

Class: jfreerails.controller.BuildTrackExplorer

Documentation

No documentation available

Source Code

public int getVertexConnectedByEdge() {
if (beforeFirst) {
throw new IllegalStateException();
}
return currentBranch.toInt();
}

setUp

Class: jfreerails.client.renderer.BuildTrackControllerTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
w = MapFixtureFactory2.getCopy();
modelRoot = new ModelRootImpl();
FreerailsPrincipal p = w.getPlayer(0).getPrincipal();
modelRoot.setup(w, p);
buildTrackController = new BuildTrackController(w, modelRoot);
MoveExecutor executor = new SimpleMoveExecutor(w, 0);
trackBuilder = new TrackMoveProducer(executor, w, modelRoot);
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
final Integer ruleID = new Integer(i);
TrackRule rule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
if (rule.getTypeName().equals("standard track")) {
singleTrackRuleID = ruleID;
}
if (rule.getTypeName().equals("double track")) {
doubleTrackRuleID = ruleID;
}
}
assertFalse(singleTrackRuleID == -1);
assertFalse(doubleTrackRuleID == -1);
// unit tests should be silent!
modelRoot.setProperty(Property.PLAY_SOUNDS, false);
}

boundsContain

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

No documentation available

Source Code

boolean boundsContain(FreerailsPrincipal p, KEY k, int index);

Called Methods

No outgoing method calls

setPathToWriteTo

Class: jfreerails.client.common.ImageManager

Documentation

No documentation available

Source Code

void setPathToWriteTo(String s);

Called Methods

No outgoing method calls

dumpImages

Class: jfreerails.client.renderer.TrackPieceRenderer

Documentation

/** Adds the images this TileRenderer uses to the specified ImageManager. */

Source Code

/** Adds the images this TileRenderer uses to the specified ImageManager. */
void dumpImages(ImageManager imageManager);

Called Methods

No outgoing method calls

set

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public void set(SKEY key, int index, FreerailsSerializable element) {
sharedLists.set(key.getKeyID(), index, element);
}

buildStation

Class: jfreerails.controller.StationBuilder

Documentation

No documentation available

Source Code

public MoveStatus buildStation(ImPoint p) {
// Only build a station if there is track at the specified point.
MoveStatus status = tryBuildingStation(p);
if (status.ok) {
FreerailsPrincipal principal = executor.getPrincipal();
AddStationPreMove preMove = AddStationPreMove.newStation(p,
this.ruleNumber, principal);
return executor.doPreMove(preMove);
}
logger.fine(status.message);
return status;
}

createReportsMenu

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

public JMenu createReportsMenu() {
reportsMenu = new javax.swing.JMenu("Reports");
JMenuItem incomeStatementJMenuItem = new JMenuItem("Income Statement");
incomeStatementJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showIncomeStatement();
}
});
JMenuItem balanceSheetJMenuItem = new JMenuItem("Balance Sheet");
balanceSheetJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showBalanceSheet();
}
});
leaderBoardJMenuItem = new JMenuItem("Leaderboard");
leaderBoardJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showLeaderBoard();
}
});
networthGraphJMenuItem = new JMenuItem("Networth Graph");
networthGraphJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showNetworthGraph();
}
});
reportsMenu.add(balanceSheetJMenuItem);
reportsMenu.add(incomeStatementJMenuItem);
reportsMenu.add(leaderBoardJMenuItem);
reportsMenu.add(networthGraphJMenuItem);
return reportsMenu;
}

startServer

Class: jfreerails.network.EchoGameServer

Documentation

/**
* Creates an EchoGameServer, starts it in a new Thread, and waits for its
* status to change to isOpen before returning.
*/

Source Code

/**
* Creates an EchoGameServer, starts it in a new Thread, and waits for its
* status to change to isOpen before returning.
*/
public static EchoGameServer startServer() {
EchoGameServer server = new EchoGameServer();
Thread t = new Thread(server);
t.start();
try {
/* Wait for the server to start before returning. */
synchronized (server.status) {
server.status.wait();
}
return server;
} catch (InterruptedException e) {
e.printStackTrace();
throw new IllegalStateException();
}
}

Called Methods

No outgoing method calls

setUp

Class: jfreerails.controller.PathOnTrackFinderTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
super.setUp();
w = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(w, 0);
ModelRoot mr = new ModelRootImpl();
producer = new TrackMoveProducer(me, w, mr);
pathFinder = new PathOnTrackFinder(w);
stationBuilder = new StationBuilder(me);
bts = BuildTrackStrategy.getDefault(w);
}

getID

Class: jfreerails.network.specifics.NewGameMessage2Server

Documentation

No documentation available

Source Code

public int getID() {
return id;
}

Called Methods

No outgoing method calls

getNumberOfTransactions

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

No documentation available

Source Code

int getNumberOfTransactions(FreerailsPrincipal p);

Called Methods

No outgoing method calls

testProductionAtEngineShopEquals

Class: jfreerails.move.ChangeProductionAtEngineShopMoveTest

Documentation

No documentation available

Source Code

public void testProductionAtEngineShopEquals() {
PlannedTrain b;
PlannedTrain c;
b = new PlannedTrain(engineType, wagons);
c = new PlannedTrain(engineType, wagons);
assertEquals(c, b);
assertEquals(b, c);
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

@Override
public String toString() {
return getTypeName();
}

findNearestCity

Class: jfreerails.controller.CalcNearestCity

Documentation

No documentation available

Source Code

public String findNearestCity() {
double cityDistance;
String cityName = null;
double tempDistance;
CityModel tempCity;
if (w.size(SKEY.CITIES) > 0) {
tempCity = (CityModel) w.get(SKEY.CITIES, 0);
cityDistance = getDistance(tempCity.getCityX(), tempCity.getCityY());
cityName = tempCity.getCityName();
for (int i = 1; i < w.size(SKEY.CITIES); i++) {
tempCity = (CityModel) w.get(SKEY.CITIES, i);
tempDistance = getDistance(tempCity.getCityX(), tempCity
.getCityY());
if (tempDistance < cityDistance) {
cityDistance = tempDistance;
cityName = tempCity.getCityName();
}
}
return cityName;
}
throw new NoSuchElementException();
}

populateTokens

Class: jfreerails.client.view.HtmlJPanel

Documentation

No documentation available

Source Code

static String populateTokens(String template, Object context) {
StringTokenizer tokenizer = new StringTokenizer(template, "$");
String output = "";
while (tokenizer.hasMoreTokens()) {
output += tokenizer.nextToken();
if (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
String value;
if (context instanceof HashMap) {
value = (String) ((HashMap) context).get(token);
} else {
try {
StringTokenizer t2 = new StringTokenizer(token, ".");
value = null;
Object o = context;
while (t2.hasMoreTokens()) {
String subToken = t2.nextToken();
Field field = o.getClass().getField(subToken);
o = field.get(o);
}
value = o.toString();
} catch (Exception e) {
e.printStackTrace();
throw new NoSuchElementException(token);
}
}
output += value;
}
}
return output;
}

Called Methods

No outgoing method calls

LocalConnection

Class: jfreerails.network.LocalConnection

Documentation

No documentation available

Source Code

public LocalConnection() {
}

Called Methods

No outgoing method calls

newWorld

Class: jfreerails.network.specifics.FreerailsClient

Documentation

/**
* Subclasses should override this method if they need to respond the the
* world being changed.
*/

Source Code

/**
* Subclasses should override this method if they need to respond the the
* world being changed.
*/
protected void newWorld(World w) {
}

Called Methods

No outgoing method calls

start

Class: jfreerails.launcher.Launcher

Documentation

/**
* Shows GUI. If <code>quickstart</code> is <code>true</code> runs the
* game.
*
* @param quickstart
* boolean
*/

Source Code

/**
* Shows GUI. If <code>quickstart</code> is <code>true</code> runs the
* game.
*
* @param quickstart
* boolean
*/
public void start(boolean quickstart) {
setVisible(true);
if (quickstart) {
startGame();
}
}

testTerminalProblem

Class: jfreerails.controller.TrackBuildingTest

Documentation

/**
* There is a bug where if a section of track has a terminal on the end, you
* cannot extend the track through the terminal. Instead, the track path
* finder finds a route that misses out the terminal.
*
*/

Source Code

/**
* There is a bug where if a section of track has a terminal on the end, you
* cannot extend the track through the terminal. Instead, the track path
* finder finds a route that misses out the terminal.
*
*/
public void testTerminalProblem() {
try {
ImPoint from = new ImPoint(5, 5);
Step[] path = { EAST, EAST, EAST };
MoveStatus ms = producer.buildTrack(from, path);
assertTrue(ms.ok);
int terminalStationType = stationBuilder.getTrackTypeID("terminal");
stationBuilder.setStationType(terminalStationType);
ms = stationBuilder.buildStation(new ImPoint(8, 5));
assertTrue(ms.ok);
pathFinder.setupSearch(new ImPoint(7, 5), new ImPoint(9, 5), bts);
pathFinder.search(-1);
path = pathFinder.pathAsVectors();
assertEquals(2, path.length);
Step[] expectedPath = { EAST, EAST };
assertTrue(Arrays.equals(expectedPath, path));
} catch (PathNotFoundException e) {
fail();
}
}

equals

Class: jfreerails.world.common.GameSpeed

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof GameSpeed) {
GameSpeed test = (GameSpeed) o;
return this.speed == test.speed;
}
return false;
}

Called Methods

No outgoing method calls

getPropertiesHtmlString

Class: jfreerails.client.view.ShowJavaProperties

Documentation

No documentation available

Source Code

public static String getPropertiesHtmlString() {
Properties p = System.getProperties();
StringBuffer sb = new StringBuffer();
/* We set the width of the table so that its text word-wraps. */
sb.append("<html><h3>Java System Properties</h3><table width =\""
+ TABLE_WIDTH + "\" align = \"left\" valign = \"top\">\n");
Enumeration keys = p.keys();
//We use an ArrayList so that the keys can be sorted into alphabetical order
ArrayList<String> list = new ArrayList<String>();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
list.add(key);
}
Collections.sort(list);
for(String key : list){
String value = p.getProperty(key);
/*
* Insert a line break after each ";". This makes reading classpath
* elements easier.
*/
value = value.replaceAll(";", ";<br>");
sb
.append("<tr><td>" + key + " </td><td> " + value
+ "</td></tr>\n");
}
sb.append("</table></html>\n");
return sb.toString();
}

Called Methods

No outgoing method calls

moveTrain

Class: jfreerails.controller.MoveTrainPreMove

Documentation

No documentation available

Source Code

private Move moveTrain(ReadOnlyWorld w) {
// Find the next vector.
Step nextVector = nextStep(w);
HashMap<TrackSection, Integer> occupiedTrackSections = occupiedTrackSections(w);
TrainMotion motion = lastMotion(w);
PositionOnTrack pot = motion.getFinalPosition();
ImPoint tile = new ImPoint(pot.getX(), pot.getY());
TrackSection desiredTrackSection = new TrackSection(nextVector, tile);
// Check whether the desired track section is single or double track.
ImPoint tileA = desiredTrackSection.tileA();
ImPoint tileB = desiredTrackSection.tileB();
FreerailsTile fta = (FreerailsTile) w.getTile(tileA.x, tileA.y);
FreerailsTile ftb = (FreerailsTile) w.getTile(tileB.x, tileB.y);
TrackPiece tpa = fta.getTrackPiece();
TrackPiece tpb = ftb.getTrackPiece();
int tracks = 1;
if (tpa.getTrackRule().isDouble() && tpb.getTrackRule().isDouble()) {
tracks = 2;
}
if (occupiedTrackSections.containsKey(desiredTrackSection)) {
int trains = occupiedTrackSections.get(desiredTrackSection);
if (trains >= tracks) {
// We need to wait for the track ahead to clear.
return stopTrain(w);
}
}
// Create a new train motion object.
TrainMotion nextMotion = nextMotion(w, nextVector);
return new NextActivityMove(nextMotion, trainID, principal);
}

jTextArea1MouseClicked

Class: jfreerails.controller.CopyableTextJPanel

Documentation

No documentation available

Source Code

private void jTextArea1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextArea1MouseClicked
if(SwingUtilities.isRightMouseButton(evt)){
jPopupMenu1.show(jTextArea1, evt.getX(), evt.getY());
}
}//GEN-LAST:event_jTextArea1MouseClicked

Called Methods

No outgoing method calls

size

Class: jfreerails.world.cargo.ImmutableCargoBundle

Documentation

No documentation available

Source Code

public int size() {
return batches.size();
}

testAdd

Class: jfreerails.controller.OpenListTest

Documentation

No documentation available

Source Code

public void testAdd() {
OpenList openList = new OpenList();
openList.add(1, 4);
assertEquals(1, openList.size());
assertEquals(4, openList.smallestF());
openList.add(1, 6);
assertEquals(1, openList.size());
assertEquals(6, openList.smallestF());
}

equals

Class: jfreerails.move.ChangeProductionAtEngineShopMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ChangeProductionAtEngineShopMove))
return false;
final ChangeProductionAtEngineShopMove changeProductionAtEngineShopMove = (ChangeProductionAtEngineShopMove) o;
if (stationNumber != changeProductionAtEngineShopMove.stationNumber)
return false;
if (after != null ? !after
.equals(changeProductionAtEngineShopMove.after)
: changeProductionAtEngineShopMove.after != null)
return false;
if (before != null ? !before
.equals(changeProductionAtEngineShopMove.before)
: changeProductionAtEngineShopMove.before != null)
return false;
if (!principal.equals(changeProductionAtEngineShopMove.principal))
return false;
return true;
}

hashCode

Class: jfreerails.move.CompositeMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
// This will do for now.
return moves.size();
}

getCategory

Class: jfreerails.world.track.TrackRuleProperties

Documentation

No documentation available

Source Code

public TrackRule.TrackCategories getCategory() {
return category;
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.world.cargo.CargoType

Documentation

No documentation available

Source Code

@Override
public String toString() {
return name;
}

Called Methods

No outgoing method calls

isStation

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

public boolean isStation() {
return false;
}

Called Methods

No outgoing method calls

moveTrain

Class: jfreerails.server.TrainUpdater

Documentation

No documentation available

Source Code

private void moveTrain(ReadOnlyWorld world, FreerailsPrincipal principal, int trainId) {
MoveTrainPreMove preMove = new MoveTrainPreMove(trainId, principal);
if (preMove.isUpdateDue(world)) {
TrainAccessor ta = new TrainAccessor(world, principal, trainId);
if (!ta.trackExists()) {
System.out.println("Track under train does not exist. Retiring train..");
this.retireTrain(world, principal, trainId);
} else {
Move m = preMove.generateMove(world);
moveReceiver.processMove(m);
}
}
}

parse

Class: jfreerails.server.parser.CargoAndTerrainParser

Documentation

No documentation available

Source Code

private static void parse(final InputSource input,
final CargoAndTerrainParser recognizer) throws SAXException,
javax.xml.parsers.ParserConfigurationException, java.io.IOException {
javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory
.newInstance();
factory.setValidating(true); // the code was generated according DTD
factory.setNamespaceAware(true); // the code was generated according
// DTD
XMLReader parser = factory.newSAXParser().getXMLReader();
parser.setContentHandler(recognizer);
parser.setErrorHandler(recognizer.getDefaultErrorHandler());
if (recognizer.resolver != null) {
parser.setEntityResolver(recognizer.resolver);
}
parser.parse(input);
}

backwardsIterator

Class: jfreerails.world.common.FreerailsPathIteratorImpl

Documentation

No documentation available

Source Code

public static FreerailsPathIterator backwardsIterator(List<Point> l) {
return new FreerailsPathIteratorImpl(l, false);
}

Called Methods

No outgoing method calls

testBoundsContain

Class: jfreerails.world.top.WorldImplTest

Documentation

No documentation available

Source Code

public void testBoundsContain(){
World w = new WorldImpl();
assertFalse(w.boundsContain(1, 1));
assertFalse(w.boundsContain(0, 0));
assertFalse(w.boundsContain(-1, -1));
w = new WorldImpl(5, 10);
assertTrue(w.boundsContain(0, 0));
assertTrue(w.boundsContain(4, 9));
assertFalse(w.boundsContain(-1, -1));
assertFalse(w.boundsContain(5, 10));
}

setCargoAtStation

Class: jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest

Documentation

No documentation available

Source Code

private void setCargoAtStation(CargoBatch cb, int amount) {
StationModel station = (StationModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
0);
MutableCargoBundle bundle = new MutableCargoBundle(getCargoAtStation());
bundle.setAmount(cb, amount);
w.set(MapFixtureFactory.TEST_PRINCIPAL, KEY.CARGO_BUNDLES, station.getCargoBundleID(), bundle
.toImmutableCargoBundle());
}

testGetDirection

Class: jfreerails.world.common.StepTest

Documentation

No documentation available

Source Code

public void testGetDirection() {
double d = 0;
assertTrue(d == n.getDirection());
d = 2 * Math.PI / 8 * 1;
assertTrue(d == ne.getDirection());
}

add

Class: jfreerails.util.List1DImpl

Documentation

No documentation available

Source Code

public int add(T element) {
elementData.add(element);
return elementData.size() - 1;
}

Called Methods

No outgoing method calls

refreshAll

Class: jfreerails.client.renderer.TrackLayer

Documentation

No documentation available

Source Code

public void refreshAll() {
}

Called Methods

No outgoing method calls

setUp

Class: jfreerails.network.specifics.FreerailsClientWithLocalServerTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
savedGamesManager = new SavedGamesManager4UnitTests();
server = new FreerailsGameServer(savedGamesManager);
}

Called Methods

No outgoing method calls

getWagonTypes

Class: jfreerails.world.station.PlannedTrain

Documentation

No documentation available

Source Code

public ImInts getWagonTypes() {
return wagonTypes;
}

Called Methods

No outgoing method calls

listUpdated

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void listUpdated(KEY key, int index, FreerailsPrincipal principal) {
// do nothing
}

Called Methods

No outgoing method calls

printStackTrack

Class: jfreerails.move.MoveStatus

Documentation

No documentation available

Source Code

public void printStackTrack(){
if(null != t)
t.printStackTrace();
}

Called Methods

No outgoing method calls

main

Class: experimental.TrackTilesGenerator

Documentation

No documentation available

Source Code

public static void main(String[] args) {
JFrame frame = new JFrame();
JScrollPane scrollPane = new JScrollPane();
frame.add(scrollPane);
TrackTilesGenerator trackTilesGenerator = new TrackTilesGenerator();
trackTilesGenerator.setPreferredSize(trackTilesGenerator
.getSize4Panel());
scrollPane.setViewportView(trackTilesGenerator);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

addD2

Class: jfreerails.util.List2DDiff

Documentation

No documentation available

Source Code

public int addD2(int d1, T element) {
return super.addElement(element, d1);
}

getScale

Class: jfreerails.client.view.MapViewJComponent

Documentation

No documentation available

Source Code

public float getScale() {
return getMapView().getScale();
}

setProperty

Class: jfreerails.controller.ClientControlInterface

Documentation

/** Sets a property, for example, the list of saved games. */

Source Code

/** Sets a property, for example, the list of saved games. */
void setProperty(ClientProperty propertyName, Serializable value);

Called Methods

No outgoing method calls

addTrack

Class: jfreerails.server.TrackMaintenanceMoveGeneratorTest

Documentation

/**
* Utility method to add the specified number of units of the specified track
* type.
*/

Source Code

/**
* Utility method to add the specified number of units of the specified track
* type.
*/
private void addTrack(int trackType, int quantity) {
AddItemTransaction t = new AddItemTransaction(
Transaction.Category.TRACK, trackType, quantity, new Money(
trackType));
w.addTransaction(MapFixtureFactory.TEST_PRINCIPAL, t);
}

toString

Class: jfreerails.client.view.PlayerDetails

Documentation

No documentation available

Source Code

@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(name);
sb.append(", ");
sb.append(networth.toString());
sb.append(" net worth, ");
sb.append(stations);
sb.append(" stations.");
return sb.toString();
}

getButtonModels

Class: jfreerails.client.common.ActionAdapter

Documentation

/**
* @return an enumeration of MappedButtonModel
*/

Source Code

/**
* @return an enumeration of MappedButtonModel
*/
public Enumeration<MappedButtonModel> getButtonModels() {
return buttonModels.elements();
}

Called Methods

No outgoing method calls

getImage

Class: jfreerails.client.common.ImageManager

Documentation

No documentation available

Source Code

Image getImage(String relativeFilename) throws IOException;

Called Methods

No outgoing method calls

handle_Produces

Class: jfreerails.server.parser.CargoAndTerrainHandlerImpl

Documentation

No documentation available

Source Code

public void handle_Produces(final Attributes meta) throws SAXException {
int cargoProduced = string2CargoID(meta.getValue("Cargo"));
int rateOfProduction = Integer.parseInt(meta.getValue("Rate"));
Production production = new Production(cargoProduced, rateOfProduction);
typeProduces.add(production);
}

listUpdated

Class: jfreerails.world.top.WorldListListener

Documentation

No documentation available

Source Code

void listUpdated(KEY key, int index, FreerailsPrincipal principal);

Called Methods

No outgoing method calls

countTrains

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

private void countTrains() {
NonNullElements trains = new NonNullElements(KEY.TRAINS, modelRoot
.getWorld(), modelRoot.getPrincipal());
boolean enabled;
if (trains.size() > 0) {
enabled = true;
} else {
enabled = false;
}
this.trainsJTabPane.setTrainTabEnabled(enabled);
this.trainListJMenuItem.setEnabled(enabled);
this.trainOrdersJMenuItem.setEnabled(enabled);
}

copyItemActionPerformed

Class: jfreerails.controller.CopyableTextJPanel

Documentation

No documentation available

Source Code

private void copyItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_copyItemActionPerformed
jTextArea1.copy();
}//GEN-LAST:event_copyItemActionPerformed

Called Methods

No outgoing method calls

equals

Class: jfreerails.move.TimeTickMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TimeTickMove))
return false;
final TimeTickMove timeTickMove = (TimeTickMove) o;
if (!newTime.equals(timeTickMove.newTime))
return false;
if (!oldTime.equals(timeTickMove.oldTime))
return false;
return true;
}

getStationRadius

Class: jfreerails.world.track.TrackRule

Documentation

No documentation available

Source Code

int getStationRadius();

Called Methods

No outgoing method calls

getStationRadius

Class: jfreerails.world.track.TrackRuleProperties

Documentation

No documentation available

Source Code

public int getStationRadius() {
return stationRadius;
}

Called Methods

No outgoing method calls

InetConnectionAccepter

Class: jfreerails.network.InetConnectionAccepter

Documentation

No documentation available

Source Code

public InetConnectionAccepter(int port, GameServer gameServer)
throws IOException {
if (null == gameServer)
throw new NullPointerException();
this.gameServer = gameServer;
serverSocket = new ServerSocket(port);
}

Called Methods

No outgoing method calls

updateInside

Class: jfreerails.client.view.MainMapAndOverviewMapMediator

Documentation

No documentation available

Source Code

private void updateInside(MouseEvent evt) {
// Rectangle r= overviewMapJPanel.mainMapVisibleRect;
boolean b = currentVisRect.contains(evt.getX(), evt.getY());
if (b != inside) {
inside = b;
if (inside) {
overviewMapJPanel.setCursor(new Cursor(Cursor.MOVE_CURSOR));
} else {
overviewMapJPanel.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
}

Called Methods

No outgoing method calls

showGameControls

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showGameControls() {
showContent(this.showControls);
}

doMove

Class: jfreerails.controller.SimpleMoveExecutor

Documentation

No documentation available

Source Code

public MoveStatus doMove(Move m) {
return m.doMove(w, p);
}

testAccount

Class: jfreerails.world.top.WorldDiffsTest

Documentation

No documentation available

Source Code

public void testAccount(){
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(0, worldDiff.numberOfMapDifferences());
assertEquals(0, worldDiff.listDiffs());
}

PathNotFoundException

Class: jfreerails.controller.PathNotFoundException

Documentation

No documentation available

Source Code

public PathNotFoundException(String arg0) {
super(arg0);
}

Called Methods

No outgoing method calls

FlowRateOutputStream

Class: jfreerails.util.FlowRateOutputStream

Documentation

No documentation available

Source Code

public FlowRateOutputStream(OutputStream out) {
this(out, "FlowRateOutputStream", 60, 1000);
}

getMaintenanceCost

Class: jfreerails.world.track.TrackRule

Documentation

No documentation available

Source Code

Money getMaintenanceCost();

Called Methods

No outgoing method calls

isMustConnect2ExistingTrack

Class: jfreerails.world.top.GameRules

Documentation

No documentation available

Source Code

public synchronized boolean isMustConnect2ExistingTrack() {
return mustConnect2ExistingTrack;
}

Called Methods

No outgoing method calls

testStops2

Class: jfreerails.controller.MoveTrainPreMove2ndTest

Documentation

/**
* Test that when the train arrives at a non scheduled station tile it stops,
* drops off and picks up cargo, then continues
*/

Source Code

/**
* Test that when the train arrives at a non scheduled station tile it stops,
* drops off and picks up cargo, then continues
*/
public void testStops2() {
// Check that there two stations on the schedule: station0 and station2;
TrainAccessor ta = new TrainAccessor(world, principal, 0);
ImmutableSchedule schedule = ta.getSchedule();
assertEquals(2, schedule.getNumOrders());
assertEquals(2, schedule.getOrder(0).getStationID());
// Check the train should have 2 wagons for cargo #0
ImInts expectedConsist = new ImInts(0, 0);
ImInts actualConsist = ta.getTrain().getConsist();
assertEquals(expectedConsist, actualConsist);
addCargoAtStation(1, 800);
// Move the train to just before station 1.
PositionOnTrack pot;
TrainMotion tm;
do {
tm = moveTrain();
pot = tm.getFinalPosition();
} while (pot.getX() < station1Location.x);
assertEquals(station1Location.x, pot.getX());
assertEquals(station1Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
// The next train motion should represent the stop at the station.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station1Location.x, pot.getX());
assertEquals(station1Location.y, pot.getY());
assertEquals(STOPPED_AT_STATION, tm.getActivity());
// 80 Units of cargo should have been transferred to the train!
CargoBundle onTrain = ta.getCargoBundle();
int amount = onTrain.getAmount(0);
assertEquals(80, amount);
// Then the train should continue.
tm = moveTrain();
pot = tm.getFinalPosition();
assertEquals(station1Location.x + 1, pot.getX());
assertEquals(station1Location.y, pot.getY());
assertEquals(READY, tm.getActivity());
}

getInput

Class: jfreerails.world.terrain.Conversion

Documentation

No documentation available

Source Code

public int getInput() {
return input;
}

Called Methods

No outgoing method calls

initComponents

Class: jfreerails.client.view.SelectEngineJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
okjButton = new javax.swing.JButton();
canceljButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
setLayout(new java.awt.GridBagLayout());
setPreferredSize(new java.awt.Dimension(400, 350));
okjButton.setText("OK");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 9, 10);
add(okjButton, gridBagConstraints);
canceljButton.setText("Cancel");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(10, 10, 10, 10);
add(canceljButton, gridBagConstraints);
jList1
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1
.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(
javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jScrollPane1.setViewportView(jList1);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}// GEN-END:initComponents

testExplorer

Class: jfreerails.controller.SimpleAStarPathFinderTest

Documentation

No documentation available

Source Code

public void testExplorer() {
setUp();
assertEquals(0, map.getPosition());
assertTrue(map.hasNextEdge());
map.nextEdge();
assertTrue(!map.hasNextEdge());
assertEquals(1, map.getVertexConnectedByEdge());
assertEquals(11, map.getEdgeCost());
map.moveForward();
assertEquals(1, map.getPosition());
assertTrue(map.hasNextEdge());
map.nextEdge();
assertEquals(0, map.getVertexConnectedByEdge());
// now try jumping to a different position.
map.setPosition(2);
assertEquals(2, map.getPosition());
assertTrue(map.hasNextEdge());
map.nextEdge();
assertEquals(5, map.getVertexConnectedByEdge());
}

gotoRow

Class: jfreerails.world.top.WorldIterator

Documentation

/** Moves the cursor to the specified index. */

Source Code

/** Moves the cursor to the specified index. */
void gotoRow(int row);

Called Methods

No outgoing method calls

end_Tile

Class: jfreerails.server.parser.CargoAndTerrainHandler

Documentation

/**
* A container element end event handling method.
*
*/

Source Code

/**
* A container element end event handling method.
*
*/
public void end_Tile() throws SAXException;

Called Methods

No outgoing method calls

itemAdded

Class: jfreerails.client.view.TrainDialogueJPanel

Documentation

No documentation available

Source Code

public void itemAdded(KEY key, int index, FreerailsPrincipal p) {
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return sizeD1();
}

testGetFirstVectorToTry

Class: jfreerails.controller.FlatTrackExplorerTest

Documentation

No documentation available

Source Code

public void testGetFirstVectorToTry() {
setUp();
PositionOnTrack p = PositionOnTrack.createComingFrom(10, 10,
Step.SOUTH_WEST);
FlatTrackExplorer fte = new FlatTrackExplorer(world, p);
Step v = fte.getFirstVectorToTry();
assertEquals(Step.EAST, v);
}

reset

Class: jfreerails.world.top.WorldIterator

Documentation

/**
* Moves the cursor to before the first element and updates any cached
* values.
*/

Source Code

/**
* Moves the cursor to before the first element and updates any cached
* values.
*/
void reset();

Called Methods

No outgoing method calls

testDropOffCargo

Class: jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest

Documentation

/**
* Tests that a train drops of cargo that a station demands and does not
* drop off cargo that is not demanded unless it has to.
*/

Source Code

/**
* Tests that a train drops of cargo that a station demands and does not
* drop off cargo that is not demanded unless it has to.
*/
public void testDropOffCargo() {
// Set the station to demand cargo type 0.
StationModel station = (StationModel) w.get(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS,
0);
Demand4Cargo demand = new Demand4Cargo(new boolean[] { true,
false, false, false });
station = new StationModel(station, demand);
w.set(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, 0, station);
// Check that the station demands what we think it does.
assertTrue("The station should demand cargo type 0.", station
.getDemand().isCargoDemanded(0));
assertFalse("The station shouldn't demand cargo type 1.", station
.getDemand().isCargoDemanded(1));
// Add 2 wagons for cargo type 0 and 1 for cargo type 1 to train.
ImInts wagons = new ImInts(0, 0, 1, 1);
addWagons(wagons);
// Add quantities of cargo type 0 and 2 to the train.
setCargoOnTrain(this.cargoType0FromStation2, 50);
setCargoOnTrain(this.cargoType1FromStation2, 40);
stopAtStation();
/*
* The train should have dropped of the 50 units cargo of type 0 since
* the station demands it but not the 40 units of cargo type 1 which is
* does not demand.
*/
MutableCargoBundle expectedOnTrain = new MutableCargoBundle();
expectedOnTrain.setAmount(this.cargoType1FromStation2, 40);
assertEquals(expectedOnTrain.toImmutableCargoBundle(),
getCargoOnTrain());
assertEquals(ImmutableCargoBundle.EMPTY_BUNDLE, getCargoAtStation());
// Now remove the wagons from the train.
removeAllWagonsFromTrain();
stopAtStation();
/*
* This time the train has no wagons, so has to drop the 40 units of
* cargo type 1 even though the station does not demand it. Since ths
* station does not demand it, it is added to the cargo waiting at the
* station.
*/
MutableCargoBundle expectedAtStation = new MutableCargoBundle();
expectedAtStation.setAmount(this.cargoType1FromStation2, 40);
assertEquals(expectedAtStation.toImmutableCargoBundle(),
getCargoAtStation());
assertEquals(ImmutableCargoBundle.EMPTY_BUNDLE, getCargoOnTrain());
}

run

Class: jfreerails.network.AbstractInetConnection

Documentation

No documentation available

Source Code

public void run() {
try {
while (true) {
FreerailsSerializable fs = inetConnection.receive();
synchronized (inbound) {
inbound.write(fs);
inbound.notifyAll();
}
}
} catch (EOFException e) {
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
logger.fine(this + "Reciprocating shutdown..");
shutDownInput();
readerThreadStatus.close();
}

hashCode

Class: jfreerails.move.AddPlayerMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return player2add.hashCode();
}

assertNextVertexIs

Class: jfreerails.controller.BuildTrackExplorerTest

Documentation

No documentation available

Source Code

private void assertNextVertexIs(Step oneTileMoveVector, int x, int y,
BuildTrackExplorer explorer) {
assertTrue(explorer.hasNextEdge());
explorer.nextEdge();
PositionOnTrack pos = new PositionOnTrack(explorer
.getVertexConnectedByEdge());
assertEquals(PositionOnTrack.createComingFrom(x, y, oneTileMoveVector),
pos);
}

TrackPathFinder

Class: jfreerails.controller.TrackPathFinder

Documentation

No documentation available

Source Code

public TrackPathFinder(ReadOnlyWorld world, FreerailsPrincipal principal) {
this.world = world;
this.principal = principal;
}

Called Methods

No outgoing method calls

testCreateInstanceIArrayIArray

Class: jfreerails.world.train.TrainPositionOnMapTest

Documentation

No documentation available

Source Code

/*
* Test for TrainPosition createInstance(int[], int[])
*/
public void testCreateInstanceIArrayIArray() {
try {
TrainPositionOnMap.createInstance(new int[] { 40, 30, 20, 10 },
new int[] { 44, 33, 22, 11 });
} catch (Exception e) {
assertTrue(false);
}
try {
TrainPositionOnMap.createInstance(new int[] { 40, 30, 20 },
new int[] { 44, 33, 22, 11 });
assertTrue(false);
} catch (Exception e) {
}
}

connect

Class: jfreerails.network.specifics.FreerailsClient

Documentation

/**
* Connects this client to a local server.
*/

Source Code

/**
* Connects this client to a local server.
*/
public final LogOnResponse connect(GameServer server, String username,
String password) {
try {
LogOnRequest request = new LogOnRequest(username, password);
connection2Server = new LocalConnection();
connection2Server.writeToServer(request);
server.addConnection((LocalConnection) connection2Server);
LogOnResponse response = (LogOnResponse) connection2Server
.waitForObjectFromServer();
return response;
} catch (Exception e) {
try {
connection2Server.disconnect();
} catch (IOException e1) {
e1.printStackTrace();
}
return LogOnResponse.rejected(e.getMessage());
}
}

paintComponent

Class: experimental.TrackTilesGenerator

Documentation

No documentation available

Source Code

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (TrackRule rule : rules) {
String typeName = rule.getTypeName();
typeName += rule.isDouble() ? " (Double) " : " (Single)";
g.drawString(typeName, 10, 10);
g.translate(0, 30);
Graphics2D g2 = (Graphics2D) g.create();
for (int i = 0; i < 512; i++) {
if (rule.testTrackPieceLegality(i)) {
String fileName = TrackPieceRendererImpl.generateFilename(
i, rule.getTypeName());
Image tile;
try {
tile = imageManager.getImage(fileName);
g2.drawImage(tile, 0, 0, null);
g2.translate(60, 0);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
g.translate(0, 60);
}
}

setup

Class: jfreerails.client.view.SelectEngineJPanel

Documentation

No documentation available

Source Code

public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
jList1.setModel(new World2ListModelAdapter(mr.getWorld(),
SKEY.ENGINE_TYPES));
jList1.setCellRenderer(new TrainCellRenderer(vl));
okjButton.addActionListener(closeAction);
}

get

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public FreerailsSerializable get(ITEM item) {
return items.get(item.getKeyID());
}

createHelpMenu

Class: jfreerails.client.top.GUIComponentFactoryTestImpl

Documentation

No documentation available

Source Code

public JMenu createHelpMenu() {
return helpMenu;
}

Called Methods

No outgoing method calls

FlowRateOutputStream

Class: jfreerails.util.FlowRateOutputStream

Documentation

No documentation available

Source Code

public FlowRateOutputStream(OutputStream out, String streamName,
int measureDuration, int measureInterval) {
super(out);
byteSentCumul = 0L;
totalByteSent = 0L;
previousTotalByteSent = 0L;
openTimeMillis = System.currentTimeMillis();
nextFree = 0;
nbUsed = 0;
running = false;
closeRequested = false;
byteSent = new long[measureDuration];
this.measureInterval = measureInterval;
this.streamName = streamName;
if (this.measureInterval == 0) {
showTrace = false;
this.measureInterval = 1000L;
} else {
showTrace = true;
}
(new Thread(this)).start();
}

Called Methods

No outgoing method calls

doProcessing

Class: jfreerails.server.CalcSupplyAtStations

Documentation

/**
*
* Loop through each known station, call calculations method.
*
*/

Source Code

/**
*
* Loop through each known station, call calculations method.
*
*/
public void doProcessing() {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
NonNullElements iterator = new NonNullElements(KEY.STATIONS, w,
principal);
while (iterator.next()) {
StationModel stationBefore = (StationModel) iterator
.getElement();
CalcCargoSupplyRateAtStation supplyRate;
supplyRate = new CalcCargoSupplyRateAtStation(w,
stationBefore.x, stationBefore.y);
StationModel stationAfter = supplyRate
.calculations(stationBefore);
if (!stationAfter.equals(stationBefore)) {
Move move = new ChangeStationMove(iterator.getIndex(),
stationBefore, stationAfter, principal);
this.moveReceiver.processMove(move);
}
}
}
}

showStationOrTerrainInfo

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showStationOrTerrainInfo(int x, int y) {
FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
TrackRule trackRule = tile.getTrackPiece().getTrackRule();
FreerailsPrincipal principal = modelRoot.getPrincipal();
if (trackRule.isStation()
&& tile.getTrackPiece().getOwnerID() == world.getID(principal)) {
for (int i = 0; i < world.size(principal, KEY.STATIONS); i++) {
StationModel station = (StationModel) world.get(principal,
KEY.STATIONS, i);
if (null != station && station.x == x && station.y == y) {
this.showStationInfo(i);
return;
}
}
throw new IllegalStateException("Couldn't find station at " + x
+ ", " + y);
}
this.showTerrainInfo(x, y);
}

getRightOfWay

Class: jfreerails.world.terrain.TileTypeImpl

Documentation

No documentation available

Source Code

public int getRightOfWay() {
return rightOfWay;
}

Called Methods

No outgoing method calls

getCategory

Class: jfreerails.world.accounts.AddItemTransaction

Documentation

No documentation available

Source Code

public Category getCategory() {
return category;
}

Called Methods

No outgoing method calls

getWagonsToAdd

Class: jfreerails.world.train.MutableSchedule

Documentation

/** Returns the wagons to add at the next scheduled stop. */

Source Code

/** Returns the wagons to add at the next scheduled stop. */
public ImInts getWagonsToAdd() {
return orders.get(nextScheduledOrder).getConsist();
}

equals

Class: jfreerails.util.List2DImpl

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object obj) {
if (!(obj instanceof List2D)) {
return false;
}
return Lists.equals(this, (List2D)obj);
}

getOverheadImage

Class: jfreerails.client.renderer.TrainImages

Documentation

No documentation available

Source Code

public Image getOverheadImage(int direction) {
return overheadImages[direction];
}

Called Methods

No outgoing method calls

showIncomeStatement

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showIncomeStatement() {
IncomeStatementHtmlJPanel bs = new IncomeStatementHtmlJPanel();
bs.setup(this.modelRoot, vl, this.closeCurrentDialogue);
this.showContent(bs);
}

addTrackRules

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void addTrackRules(World w) {
for (int i = 0; i < this.ruleList.size(); i++) {
TrackRule r = ruleList.get(i);
w.add(SKEY.TRACK_RULES, r);
}
}

removeLast

Class: jfreerails.util.List1DImpl

Documentation

No documentation available

Source Code

public T removeLast() {
int last = elementData.size() - 1;
return elementData.remove(last);
}

Called Methods

No outgoing method calls

tilesChanged

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

/**
* Listens for changes on the map, for instance when track is built, and
* refreshes the map views.
*/

Source Code

/**
* Listens for changes on the map, for instance when track is built, and
* refreshes the map views.
*/
public void tilesChanged(Rectangle tilesChanged) {
logger.fine("TilesChanged = " + tilesChanged);
// If lots of tiles have changed, do a complete refresh.
int size = tilesChanged.width * tilesChanged.height;
if (size > 100) {
mainMap.refreshAll();
overviewMap.refreshAll();
} else {
Point tile = new Point();
// Fix for bug 967673 (Crash when building track close to edge of
// map).
Rectangle mapRect = new Rectangle(0, 0, world.getMapWidth(), world
.getMapHeight());
tilesChanged = tilesChanged.intersection(mapRect);
for (tile.x = tilesChanged.x; tile.x < (tilesChanged.x + tilesChanged.width); tile.x++) {
for (tile.y = tilesChanged.y; tile.y < (tilesChanged.y + tilesChanged.height); tile.y++) {
mainMap.refreshTile(tile.x, tile.y);
overviewMap.refreshTile(tile.x, tile.y);
}
}
}
}

RemoveItemFromListMove

Class: jfreerails.move.RemoveItemFromListMove

Documentation

No documentation available

Source Code

RemoveItemFromListMove(KEY k, int i, FreerailsSerializable item,
FreerailsPrincipal p) {
this.item = item;
this.listKey = k;
this.index = i;
this.principal = p;
}

Called Methods

No outgoing method calls

getTile

Class: jfreerails.world.top.WorldDiffs

Documentation

No documentation available

Source Code

@Override
public FreerailsSerializable getTile(int x, int y) {
ImPoint p = new ImPoint(x, y);
if (this.mapDiff.containsKey(p)) {
return (FreerailsSerializable) this.mapDiff.get(p);
}
return underlying.getTile(x, y);
}

dumpImages

Class: jfreerails.client.renderer.NullTrackPieceRenderer

Documentation

No documentation available

Source Code

public void dumpImages(ImageManager imageManager) {
// TODO Auto-generated method stub
}

Called Methods

No outgoing method calls

undoMove

Class: jfreerails.move.AddItemToListMove

Documentation

No documentation available

Source Code

public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.isOk()) {
w.removeLast(this.principal, listKey);
}
return ms;
}

testToInt

Class: jfreerails.world.common.PositionOnTrackTest

Documentation

No documentation available

Source Code

public void testToInt() {
PositionOnTrack p1 = PositionOnTrack.createComingFrom(10, 20,
Step.NORTH);
PositionOnTrack p2 = PositionOnTrack.createComingFrom(10, 30,
Step.NORTH);
assertTrue(p1.toInt() != p2.toInt());
}

setup

Class: jfreerails.client.view.CashJLabel

Documentation

No documentation available

Source Code

public void setup(ModelRoot model, RenderersRoot vl,
Action closeAction) {
this.w = model.getWorld();
principal = model.getPrincipal();
}

setup

Class: jfreerails.client.view.MapViewJComponentConcrete

Documentation

No documentation available

Source Code

public void setup(MapRenderer mv, ModelRootImpl mr, RenderersRoot rr)
throws IOException {
super.setMapView(mv);
this.setBorder(null);
this.mapCursor = new FreerailsCursor(mr, rr);
mr.addPropertyChangeListener(this);
}

tryDoMove

Class: jfreerails.move.CompositeMove

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
// Since whether a move later in the list goes through could
// depend on whether an earlier move has been executed, we need
// actually execute moves, then undo them to test whether the
// array of moves can be executed ok.
MoveStatus ms = doMove(w, p);
if (ms.ok) {
// We just wanted to see if we could do them so we undo them again.
undoMoves(w, moves.size() - 1, p);
}
// If its not ok, then doMove would have undone the moves so we don't
// need to undo them.
return ms;
}

refreshAll

Class: jfreerails.client.view.DetailMapRenderer

Documentation

No documentation available

Source Code

public void refreshAll() {
background.refreshAll();
}

hashCode

Class: jfreerails.world.common.ImStringList

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return strings.length;
}

Called Methods

No outgoing method calls

getSingleRuleInstance

Class: jfreerails.controller.BuildTrackStrategy

Documentation

No documentation available

Source Code

public static BuildTrackStrategy getSingleRuleInstance(int trackTypeID,
ReadOnlyWorld w) {
int noTerrainTypes = w.size(SKEY.TERRAIN_TYPES);
int[] newRules = new int[noTerrainTypes];
for (int i = 0; i < noTerrainTypes; i++) {
newRules[i] = trackTypeID;
}
return new BuildTrackStrategy(newRules);
}

getStatus

Class: jfreerails.controller.TrainAccessor

Documentation

No documentation available

Source Code

public SpeedTimeAndStatus.TrainActivity getStatus(double time){
TrainMotion tm = findCurrentMotion(time);
return tm.getActivity();
}

getBonds

Class: jfreerails.controller.FinancialDataGatherer

Documentation

No documentation available

Source Code

public int getBonds() {
return bonds;
}

Called Methods

No outgoing method calls

getBuildTrackChangeTrackPieceMove

Class: jfreerails.move.ChangeTrackPieceCompositeMove

Documentation

No documentation available

Source Code

// utility method.
private static ChangeTrackPieceMove getBuildTrackChangeTrackPieceMove(
ImPoint p, Step direction, TrackRule trackRule, ReadOnlyWorld w,
FreerailsPrincipal principal) {
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
int owner = getOwner(principal, w);
if (w.boundsContain(p.x, p.y)) {
oldTrackPiece = ((FreerailsTile) w.getTile(p.x, p.y))
.getTrackPiece();
if (oldTrackPiece.getTrackRule() != NullTrackType.getInstance()) {
TrackConfiguration trackConfiguration = TrackConfiguration.add(
oldTrackPiece.getTrackConfiguration(), direction);
newTrackPiece = new TrackPieceImpl(trackConfiguration,
oldTrackPiece.getTrackRule(), owner, oldTrackPiece
.getTrackTypeID());
} else {
newTrackPiece = getTrackPieceWhenOldTrackPieceIsNull(direction,
trackRule, owner, findRuleID(trackRule, w));
}
} else {
newTrackPiece = getTrackPieceWhenOldTrackPieceIsNull(direction,
trackRule, owner, findRuleID(trackRule, w));
oldTrackPiece = NullTrackPiece.getInstance();
}
return new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece, p);
}

addSupplyAndDemand

Class: jfreerails.controller.AddStationPreMove

Documentation

No documentation available

Source Code

private CompositeMove addSupplyAndDemand(CompositeMove m, ReadOnlyWorld w) {
ImList<Move> moves2 = m.getMoves();
Move[] moves = new Move[moves2.size()];
for (int i = 0; i < moves2.size(); i++) {
moves[i] = moves2.get(i);
}
for (int i = 0; i < moves.length; i++) {
if (moves[i] instanceof AddItemToListMove) {
AddItemToListMove move = (AddItemToListMove) moves[i];
if (move.getKey().equals(KEY.STATIONS)) {
StationModel station = (StationModel) move.getAfter();
CalcCargoSupplyRateAtStation supplyRate;
supplyRate = new CalcCargoSupplyRateAtStation(w, station.x,
station.y, ruleNumber);
StationModel stationAfter = supplyRate
.calculations(station);
moves[i] = new AddItemToListMove(move.getKey(), move
.getIndex(), stationAfter, move.getPrincipal());
}
}
}
return new CompositeMove(moves);
}

trackExists

Class: jfreerails.controller.TrainAccessor

Documentation

/**
* Checks the track under the train's final position still exists (i.e.
* has not been bulldozed).
*/

Source Code

/**
* Checks the track under the train's final position still exists (i.e.
* has not been bulldozed).
*/
public boolean trackExists() {
ActivityIterator ai = w.getActivities(p, id);
ai.gotoLastActivity();
TrainMotion tm = (TrainMotion) ai.getActivity();
PositionOnTrack pot = tm.getFinalPosition();
int x = pot.getX();
int y = pot.getY();
FreerailsTile tile = (FreerailsTile) w.getTile(x, y);
TrackPiece trackPiece = tile.getTrackPiece();
TrackConfiguration present = trackPiece.getTrackConfiguration();
TrackConfiguration needed = TrackConfiguration.getFlatInstance(pot.cameFrom());
return present.contains(needed);
}

getTicks

Class: jfreerails.world.common.GameCalendar

Documentation

No documentation available

Source Code

public int getTicks(int year) {
int deltaYear = year - startYear;
return deltaYear * ticksPerYear;
}

Called Methods

No outgoing method calls

BondTransaction

Class: jfreerails.world.accounts.BondTransaction

Documentation

No documentation available

Source Code

private BondTransaction(Category category, int type, int quantity,
Money amount) {
super(category, type, quantity, amount);
}

equals

Class: jfreerails.util.ListKey

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ListKey))
return false;
final ListKey listKey = (ListKey) o;
if (!Arrays.equals(index, listKey.index))
return false;
if (!listID.equals(listKey.listID))
return false;
if (!type.equals(listKey.type))
return false;
return true;
}

Called Methods

No outgoing method calls

findPathElementsInJar

Class: jfreerails.util.ClassPath

Documentation

/**
* Finds all path elements in the supplied JAR and returns them as a list
*
* @param man
* the manifest of the given jar
* @param jar
* the jar associated with the given manifest.
*/

Source Code

/**
* Finds all path elements in the supplied JAR and returns them as a list
*
* @param man
* the manifest of the given jar
* @param jar
* the jar associated with the given manifest.
*/
protected LinkedList<String> findPathElementsInJar(Manifest man,
JarFile jar, File jarFile) {
LinkedList<String> result = new LinkedList<String>();
Attributes atts = man.getMainAttributes();
Set keys = atts.keySet();
Iterator i = keys.iterator();
while (i.hasNext()) {
Object key = i.next();
String value = (String) atts.get(key);
logger.fine(jar.getName() + " " + key + ": " + value);
if (key.toString().equals("Class-Path")) {
logger.info("scanning " + jar.getName()
+ "'s manifest classpath: " + value);
StringTokenizer toke = new StringTokenizer(value);
while (toke.hasMoreTokens()) {
String element = toke.nextToken();
if (jarFile.getParent() == null)
result.add(element);
else {
result.add(jarFile.getParent() + File.separator
+ element);
}
}
}
}
return result;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.accounts.AddItemTransaction

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = category.hashCode();
result = 29 * result + type;
result = 29 * result + quantity;
result = 29 * result + amount.hashCode();
return result;
}

getFixedCost

Class: jfreerails.world.track.TrackRule

Documentation

No documentation available

Source Code

Money getFixedCost();

Called Methods

No outgoing method calls

getPossiblePositions

Class: jfreerails.controller.FlatTrackExplorer

Documentation

/**
* @return an array of PositionOnTrack objects describing the set of
* possible orientations at this position (heading towards the
* center of the tile)
* @param p
* location of track to consider.
*/

Source Code

/**
* @return an array of PositionOnTrack objects describing the set of
* possible orientations at this position (heading towards the
* center of the tile)
* @param p
* location of track to consider.
*/
public static PositionOnTrack[] getPossiblePositions(ReadOnlyWorld w,
ImPoint p) {
TrackPiece tp = ((FreerailsTile) w.getTile(p.x, p.y)).getTrackPiece();
TrackConfiguration conf = tp.getTrackConfiguration();
Step[] vectors = Step.getList();
// Count the number of possible positions.
int n = 0;
for (int i = 0; i < vectors.length; i++) {
if (conf.contains(vectors[i].get9bitTemplate())) {
n++;
}
}
PositionOnTrack[] possiblePositions = new PositionOnTrack[n];
n = 0;
for (int i = 0; i < vectors.length; i++) {
if (conf.contains(vectors[i].get9bitTemplate())) {
possiblePositions[n] = PositionOnTrack.createComingFrom(p.x,
p.y, vectors[i].getOpposite());
n++;
}
}
return possiblePositions;
}

setup

Class: jfreerails.client.view.MapViewJComponentConcrete

Documentation

No documentation available

Source Code

public void setup(MapRenderer mv) {
super.setMapView(mv);
}

hideErrorMessages

Class: jfreerails.launcher.LauncherInterface

Documentation

No documentation available

Source Code

void hideErrorMessages();

Called Methods

No outgoing method calls

getConversion

Class: jfreerails.world.terrain.TerrainType

Documentation

No documentation available

Source Code

ImList<Conversion> getConversion();

Called Methods

No outgoing method calls

overallRateString

Class: jfreerails.util.FlowRateOutputStream

Documentation

No documentation available

Source Code

public String overallRateString() throws IOException {
double d = totalByteSent / 1024D
/ ((System.currentTimeMillis() - openTimeMillis) / 1000D);
return decimalFormat.format(d);
}

Called Methods

No outgoing method calls

hasNext

Class: jfreerails.world.train.PathWalkerImpl

Documentation

/**
* @return true if there is still some distance to go along this path
*/

Source Code

/**
* @return true if there is still some distance to go along this path
*/
public boolean hasNext() {
if (0 == distanceOfThisStepRemaining) {
return false;
} else if (distanceAlongCurrentSegment < currentSegment.getLength()) {
return true;
} else if (it.hasNext()) {
return true;
} else {
return false;
}
}

hashCode

Class: jfreerails.world.common.ImHashSet

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return hashSet.hashCode();
}

Called Methods

No outgoing method calls

addElement

Class: jfreerails.util.ListXDDiffs

Documentation

No documentation available

Source Code

public int addElement(T element, int... dim) {
int sizeBefore = size(dim);
int[] index = add2Array(dim, sizeBefore);
setElementDiff: {
if (getUnderlyingSize(dim) > sizeBefore) {
T uElement = uGet(index);
if (Utils.equal(uElement, element)) {
// We are reading an element that was removed, in which
// case we don't store a diff.
break setElementDiff;
}
}
ListKey elementKey = new ListKey(ListKey.Type.Element, listID,
index);
diffs.put(elementKey, element);
}
setSize(sizeBefore + 1, dim);
return sizeBefore;
}

setUp

Class: jfreerails.client.view.IncomeStatementGeneratorTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
w = new WorldImpl();
w.addPlayer(MapFixtureFactory.TEST_PLAYER);
MapFixtureFactory.generateCargoTypesList(w);
balanceSheetGenerator = new IncomeStatementGenerator(w,
MapFixtureFactory.TEST_PRINCIPAL);
}

setup

Class: jfreerails.client.view.TrainDescriptionJPanel

Documentation

No documentation available

Source Code

public void setup(ModelRoot mr, RenderersRoot vl,
Action closeAction) {
this.trainViewJPanel1.setup(mr, vl, closeAction);
trainViewJPanel1.setHeight(30);
trainViewJPanel1.setCenterTrain(true);
this.w = mr.getWorld();
principal = mr.getPrincipal();
}

testStartSearchOnSharpCurve

Class: jfreerails.controller.TrackBuildingTest

Documentation

/**
* There is a bug where if you try to start building track on a 90 degree
* bend, no track path is found even when one should exist.
*
*/

Source Code

/**
* There is a bug where if you try to start building track on a 90 degree
* bend, no track path is found even when one should exist.
*
*/
public void testStartSearchOnSharpCurve() {
try {
ImPoint from = new ImPoint(5, 5);
Step[] path = { EAST, SOUTH };
MoveStatus ms = producer.buildTrack(from, path);
assertTrue(ms.ok);
pathFinder.setupSearch(new ImPoint(6, 5), new ImPoint(6, 7), bts);
pathFinder.search(-1);
path = pathFinder.pathAsVectors();
assertEquals(2, path.length);
assertEquals(SOUTH, path[0]);
assertEquals(SOUTH, path[1]);
} catch (PathNotFoundException e) {
fail();
}
}

validateInput

Class: jfreerails.launcher.ClientOptionsJPanel

Documentation

No documentation available

Source Code

public boolean validateInput() {
/* Validate player name. */
if (playerName.getText() == null || playerName.getText().equals("")) {
owner.setInfoText("Please set a name for your player",
LauncherInterface.ERROR);
return false;
}
/* Validate host name. */
if (remoteIP.getText() == null || remoteIP.getText().equals("")) {
owner.setInfoText("Please enter a host name",
LauncherInterface.ERROR);
return false;
}
/* Validate port. */
try {
int port = Integer.parseInt(remotePort.getText());
if (port < 0 || port > 65535) {
owner.setInfoText(INVALID_PORT, LauncherInterface.ERROR);
return false;
}
} catch (Exception e) {
owner.setInfoText(INVALID_PORT, LauncherInterface.ERROR);
return false;
}
/*
* Validate display-mode selection. Note, on some systems the display
* mode can't be changed, in which case the list of selectable display
* modes will have length 0.
*/
if (fullScreenButton.isSelected() && jList1.getModel().getSize() > 0
&& jList1.getSelectedIndex() == -1) {
owner
.setInfoText("Select a display-mode.",
LauncherInterface.ERROR);
return false;
}
/* Everything is ok. */
owner.hideErrorMessages();
owner.setProperty("freerails.server.port", this.remotePort.getText());
owner.setProperty("freerails.player.name", this.playerName.getText());
owner.setProperty("freerails.server.ip.address", this.remoteIP.getText());
owner.saveProps();
return true;
}

hideErrorMessages

Class: jfreerails.launcher.Launcher

Documentation

No documentation available

Source Code

public void hideErrorMessages() {
if (infoLabel.getIcon() == errorIcon) {
infoLabel.setText(null);
infoLabel.setIcon(null);
nextButton.setEnabled(true);
}
}

Called Methods

No outgoing method calls

paintComponent

Class: jfreerails.client.view.TrainDescriptionJPanel

Documentation

No documentation available

Source Code

@Override
protected void paintComponent(Graphics arg0) {
//Check whether the train or its cargo have changed since the last call to this method.
updateIfNecessary();
super.paintComponent(arg0);
}

testGetPossiblePositions

Class: jfreerails.controller.FlatTrackExplorerTest

Documentation

No documentation available

Source Code

public void testGetPossiblePositions() {
setUp();
PositionOnTrack[] positions = FlatTrackExplorer.getPossiblePositions(
world, new ImPoint(10, 10));
assertNotNull(positions);
assertEquals(3, positions.length);
HashSet<Step> directions = new HashSet<Step>();
directions.add(Step.WEST);
directions.add(Step.EAST);
directions.add(Step.SOUTH_WEST);
HashSet<Step> directions2 = new HashSet<Step>();
for (int i = 0; i < positions.length; i++) {
directions2.add(positions[i].cameFrom());
}
assertEquals(directions, directions2);
}

dispatchEvent

Class: jfreerails.client.top.SynchronizedEventQueue

Documentation

No documentation available

Source Code

@Override
protected void dispatchEvent(AWTEvent aEvent) {
synchronized (MUTEX) {
try {
super.dispatchEvent(aEvent);
} catch (Exception e) {
/*
* If something goes wrong, lets kill the game straight away to
* avoid hard-to-track-down bugs.
*/
ReportBugTextGenerator.unexpectedException(e);
}
}
}

setAmount

Class: jfreerails.world.cargo.MutableCargoBundle

Documentation

No documentation available

Source Code

public void setAmount(CargoBatch cb, int amount) {
if (0 == amount) {
sortedMap.remove(cb);
} else {
sortedMap.put(cb, new Integer(amount));
}
updateID++;
}

Called Methods

No outgoing method calls

selectTileIcon

Class: jfreerails.client.renderer.ChequeredTileRenderer

Documentation

No documentation available

Source Code

@Override
public int selectTileIcon(int x, int y, ReadOnlyWorld w) {
return (x + y) % 2;
}

Called Methods

No outgoing method calls

WorldDiffs

Class: jfreerails.world.top.WorldDiffs

Documentation

No documentation available

Source Code

public WorldDiffs(ReadOnlyWorld row){
listDiff = new TreeMap<ListKey, Object>();
mapDiff = new HashMap<ImPoint, Object>();
//Bit of a hack but it's not clear there is a better way, LL
underlying = (WorldImpl)row;
activityLists = new List3DDiff<ActivityAndTime>(listDiff,
underlying.activityLists, LISTID.ACTIVITY_LISTS);
bankAccounts = new List2DDiff<TransactionAndTimeStamp>(listDiff,
underlying.bankAccounts, LISTID.BANK_ACCOUNTS);
currentBalance = new List1DDiff<Money>(listDiff,
underlying.currentBalance, LISTID.CURRENT_BALANCE);
items = new List1DDiff<FreerailsSerializable>(listDiff,
underlying.items, LISTID.ITEMS);
lists = new List3DDiff<FreerailsSerializable>(listDiff,
underlying.lists, LISTID.LISTS);
players = new List1DDiff<Player>(listDiff, underlying.players,
LISTID.PLAYERS);
sharedLists = new List2DDiff<FreerailsSerializable>(listDiff,
underlying.sharedLists, LISTID.SHARED_LISTS);
time = underlying.time;
}

Called Methods

No outgoing method calls

ConvertedAtStation

Class: jfreerails.world.station.ConvertedAtStation

Documentation

No documentation available

Source Code

public ConvertedAtStation(int[] convertedTo) {
this.convertedTo = new ImInts(convertedTo);
}

Called Methods

No outgoing method calls

actionPerformed

Class: jfreerails.client.view.Unknown

Documentation

No documentation available

Source Code

public void actionPerformed(ActionEvent arg0) {
}

Called Methods

No outgoing method calls

ActionAdapter

Class: jfreerails.client.common.ActionAdapter

Documentation

/**
* An array of the actions to be used. The ComboBoxModel objects are taken
* from the NAME property of the Action. The ButtonModel icons are obtained
* from the SMALL_ICON property.
*/

Source Code

/**
* An array of the actions to be used. The ComboBoxModel objects are taken
* from the NAME property of the Action. The ButtonModel icons are obtained
* from the SMALL_ICON property.
*/
public ActionAdapter(Action[] actions) {
super();
this.actions = actions;
buttonModels = new Vector<MappedButtonModel>();
for (int i = 0; i < actions.length; i++) {
buttonModels.add(new MappedButtonModel(actions[i]));
addElement(actions[i].getValue(Action.NAME));
}
initialised = true;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.move.MoveStatus

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof MoveStatus))
return false;
final MoveStatus moveStatus = (MoveStatus) o;
if (ok != moveStatus.ok)
return false;
if (message != null ? !message.equals(moveStatus.message)
: moveStatus.message != null)
return false;
return true;
}

Called Methods

No outgoing method calls

main

Class: jfreerails.world.train.SimplePathIteratorImplTest

Documentation

No documentation available

Source Code

public static void main(String[] args) {
junit.textui.TestRunner.run(SimplePathIteratorImplTest.class);
}

Called Methods

No outgoing method calls

assertDifferent

Class: jfreerails.world.terrain.MiscTest

Documentation

No documentation available

Source Code

private void assertDifferent(Object a, Object b) {
assertFalse(a.equals(b));
assertFalse(a.hashCode() == b.hashCode());
}

Called Methods

No outgoing method calls

removeLastD3

Class: jfreerails.util.List3D

Documentation

No documentation available

Source Code

T removeLastD3(int d1, int d2);

Called Methods

No outgoing method calls

fromServer

Class: jfreerails.network.specifics.MovePrecommitter

Documentation

No documentation available

Source Code

void fromServer(Move m) {
logger.finest("Move from server: " + m.toString());
rollBackPrecommittedMoves();
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
if (!ms.ok) {
throw new IllegalStateException(ms.message);
}
}

calTotal

Class: jfreerails.client.view.IncomeStatementGenerator

Documentation

No documentation available

Source Code

private Money calTotal(Transaction.Category transactionCategory) {
long amount = 0;
for (int i = 0; i < w.getNumberOfTransactions(this.principal); i++) {
Transaction t = w.getTransaction(principal, i);
GameTime time = w.getTransactionTimeStamp(principal, i);
if (t.getCategory() == transactionCategory
&& cal.getYear(time.getTicks()) >= this.startyear) {
amount += t.deltaCash().getAmount();
}
}
return new Money(amount);
}

equals

Class: jfreerails.world.top.TestActivity

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TestActivity))
return false;
final TestActivity testActivity = (TestActivity) o;
if (duration != testActivity.duration)
return false;
return true;
}

Called Methods

No outgoing method calls

getDisplayName

Class: jfreerails.world.terrain.TileTypeImpl

Documentation

/** Returns the name, replacing any underscores with spaces. */

Source Code

/** Returns the name, replacing any underscores with spaces. */
public String getDisplayName() {
return terrainType.replace('_', ' ');
}

Called Methods

No outgoing method calls

rotateTrackNodeClockwise

Class: jfreerails.world.track.EightRotationsOfTrackPieceProducer

Documentation

No documentation available

Source Code

private static boolean[][] rotateTrackNodeClockwise(boolean[][] source) {
Point[][] grabValueFrom = new Point[3][];
grabValueFrom[0] = new Point[] { new Point(0, 1), new Point(0, 0),
new Point(1, 0) };
grabValueFrom[1] = new Point[] { new Point(0, 2), new Point(1, 1),
new Point(2, 0) };
grabValueFrom[2] = new Point[] { new Point(1, 2), new Point(2, 2),
new Point(2, 1) };
/*
* I think there is a neater way of doing this, let me know if you know
* it! Luke
*/
boolean[][] output = new boolean[3][3];
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
Point point = grabValueFrom[y][x];
/*
* y,x because of the way I defined grabValueFrom[][] above.
*/
output[x][y] = source[point.x][point.y];
}
}
return output;
}

Called Methods

No outgoing method calls

setupWagonsPopup

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void setupWagonsPopup() {
addWagonJMenu.removeAll(); // Remove existing menu items.
NonNullElements cargoTypes = new NonNullElements(SKEY.CARGO_TYPES,
modelRoot.getWorld());
while (cargoTypes.next()) {
final CargoType wagonType = (CargoType) cargoTypes.getElement();
JMenuItem wagonMenuItem = new JMenuItem();
final int wagonTypeNumber = cargoTypes.getIndex();
wagonMenuItem.setText(wagonType.getDisplayName());
Image image = vl.getWagonImages(wagonTypeNumber).getSideOnImage();
int height = image.getHeight(null);
int width = image.getWidth(null);
int scale = height / 10;
ImageIcon icon = new ImageIcon(image.getScaledInstance(width
/ scale, height / scale, Image.SCALE_FAST));
wagonMenuItem.setIcon(icon);
wagonMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(
java.awt.event.ActionEvent evt) {
addWagon(wagonTypeNumber);
}
});
addWagonJMenu.add(wagonMenuItem);
}
}

toString

Class: jfreerails.move.AddItemToListMove

Documentation

No documentation available

Source Code

@Override
public String toString() {
StringBuffer sb = new StringBuffer(this.getClass().getName());
sb.append("\n list=");
sb.append(listKey.toString());
sb.append("\n index =");
sb.append(index);
sb.append("\n item =");
sb.append(item);
return sb.toString();
}

addUrbanTile

Class: jfreerails.server.CityTilePositioner

Documentation

No documentation available

Source Code

private void addUrbanTile(CityEconomicModel city) {
int tileTypeNo = random.nextInt(urbanTerrainTypes.size());
TerrainType type = urbanTerrainTypes.get(tileTypeNo);
city.addTile(type);
}

generateCargoTypesList

Class: jfreerails.world.top.MapFixtureFactory

Documentation

/** Adds hard coded cargo types. */

Source Code

/** Adds hard coded cargo types. */
public static void generateCargoTypesList(World world) {
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Mail", Categories.Mail));
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Passengers",
Categories.Passengers));
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Goods",
Categories.Fast_Freight));
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Steel",
Categories.Slow_Freight));
world.add(SKEY.CARGO_TYPES, new CargoType(0, "Coal",
Categories.Bulk_Freight));
}

BalanceSheetGenerator

Class: jfreerails.controller.BalanceSheetGenerator

Documentation

No documentation available

Source Code

public BalanceSheetGenerator(ReadOnlyWorld w, FreerailsPrincipal principal) {
this.w = w;
this.principal = principal;
cal = (GameCalendar) w.get(ITEM.CALENDAR);
// Calculate totals
GameTime time = w.currentTime();
final int startyear = cal.getYear(time.getTicks());
year = String.valueOf(startyear);
GameTime startOfYear = new GameTime(cal.getTicks(startyear));
GameTime[] totalTimeInterval = new GameTime[] { GameTime.BIG_BANG,
GameTime.END_OF_THE_WORLD };
total = new Stats(w, principal, totalTimeInterval);
GameTime[] ytdTimeInterval = new GameTime[] { startOfYear,
GameTime.END_OF_THE_WORLD };
ytd = new Stats(w, principal, ytdTimeInterval);
}

hasPriorityOrders

Class: jfreerails.world.train.Schedule

Documentation

No documentation available

Source Code

boolean hasPriorityOrders();

Called Methods

No outgoing method calls

buildTrack

Class: jfreerails.controller.BuildTrackExplorerTest

Documentation

No documentation available

Source Code

private void buildTrack(int x, int y, Step direction) {
TrackRule rule = (TrackRule) world.get(SKEY.TRACK_RULES, 0);
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(new ImPoint(x, y), direction, rule,
rule, world, MapFixtureFactory.TEST_PRINCIPAL);
MoveStatus ms = move.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.ok);
}

jList1ValueChanged

Class: jfreerails.client.view.TrainListJPanel

Documentation

No documentation available

Source Code

private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {// GEN-FIRST:event_jList1ValueChanged
// if a train is selected, enable the 'show details' button.
if (jList1.getSelectedIndex() != -1) {
this.showDetails.setEnabled(true);
} else {
this.showDetails.setEnabled(false);
}
}// GEN-LAST:event_jList1ValueChanged

Called Methods

No outgoing method calls

getIndex

Class: jfreerails.world.train.CompositeSpeedAgainstTime

Documentation

No documentation available

Source Code

private TandI getIndex(double t) {
checkT(t);
double tSoFar = 0;
for (int i = 0; i < values.size(); i++) {
SpeedAgainstTime acc = values.get(i);
if (t <= (tSoFar + acc.getT())) {
double offset = t - tSoFar;
return new TandI(i, offset);
}
tSoFar += acc.getT();
}
// Should never happen since we call checkT() above!
throw new IllegalStateException(String.valueOf(t));
}

readResolve

Class: jfreerails.world.top.ITEM

Documentation

No documentation available

Source Code

private Object readResolve() throws ObjectStreamException {
return keys[this.keyNumber];
}

Called Methods

No outgoing method calls

getWorld

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public ReadOnlyWorld getWorld() {
return world;
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.world.player.Player

Documentation

No documentation available

Source Code

@Override
public String toString() {
return name;
}

Called Methods

No outgoing method calls

AddItemToListMove

Class: jfreerails.move.AddItemToListMove

Documentation

No documentation available

Source Code

public AddItemToListMove(KEY key, int i, FreerailsSerializable item,
FreerailsPrincipal p) {
this.listKey = key;
this.index = i;
this.item = item;
this.principal = p;
}

Called Methods

No outgoing method calls

paint

Class: jfreerails.client.view.TrainListJPanel

Documentation

No documentation available

Source Code

@Override
public void paint(Graphics g) {
if (null != world) {
NonNullElements trains = new NonNullElements(KEY.TRAINS, world,
principal);
int newNumberOfTrains = trains.size();
if (newNumberOfTrains != this.lastNumberOfTrains) {
jList1.setModel(new World2ListModelAdapter(world, KEY.TRAINS,
principal));
if (newNumberOfTrains > 0) {
jList1.setSelectedIndex(0);
}
lastNumberOfTrains = newNumberOfTrains;
}
}
super.paint(g);
}

upgradeTrack

Class: jfreerails.controller.TrackMoveProducer

Documentation

No documentation available

Source Code

private MoveStatus upgradeTrack(ImPoint point, int trackRuleID) {
ReadOnlyWorld w = executor.getWorld();
TrackPiece before = ((FreerailsTile) w.getTile(point.x, point.y)).getTrackPiece();
/* Check whether there is track here. */
if (before.getTrackTypeID() == NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
return MoveStatus.moveFailed("No track to upgrade.");
}
FreerailsPrincipal principal = executor.getPrincipal();
int owner = ChangeTrackPieceCompositeMove.getOwner(principal, w);
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, trackRuleID);
TrackPiece after = new TrackPieceImpl(before.getTrackConfiguration(),
trackRule, owner, trackRuleID);
/* We don't want to 'upgrade' a station to track. See bug 874416. */
if (before.getTrackRule().isStation()) {
return MoveStatus
.moveFailed("No need to upgrade track at station.");
}
Move move = UpgradeTrackMove.generateMove(before, after, point);
Move move2 = transactionsGenerator.addTransactions(move);
return sendMove(move2);
}

SelectMapJPanel

Class: jfreerails.launcher.SelectMapJPanel

Documentation

No documentation available

Source Code

SelectMapJPanel(LauncherInterface owner) {
this.owner = owner;
initComponents();
/* initialise the map list */
SavedGamesManagerImpl sgm = new SavedGamesManagerImpl();
newmapsJList.setListData(sgm.getNewMapNames());
newmapsJList.setSelectedIndex(0);
savedmapsJList.setListData(sgm.getSaveGameNames());
owner.setNextEnabled(true);
// Listen for changes in the server port text box.
serverPort.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
validateInput();
}
public void removeUpdate(DocumentEvent e) {
validateInput();
}
public void changedUpdate(DocumentEvent e) {
validateInput();
}
});
}

setup

Class: jfreerails.client.view.BrokerScreenHtmlJFrame

Documentation

No documentation available

Source Code

@Override
public void setup(final ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
super.setup(modelRoot, vl, closeAction);
financialDataGatherer = new FinancialDataGatherer(modelRoot.getWorld(),
modelRoot.getPrincipal());
this.modelRoot = modelRoot;
setupStockMenu();
updateHtml();
// Sets up the BrokerScreen and Adds ActionListeners to the Menu
issueBond.setAction(issueBondAction);
repayBond.setAction(repayBondAction);
}

string2CargoID

Class: jfreerails.server.parser.CargoAndTerrainHandlerImpl

Documentation

/** Returns the index number of the cargo with the specified name. */

Source Code

/** Returns the index number of the cargo with the specified name. */
private int string2CargoID(String cargoName) throws SAXException {
if (cargoName2cargoTypeNumber.containsKey(cargoName)) {
Integer integer = cargoName2cargoTypeNumber.get(cargoName);
return integer.intValue();
}
throw new SAXException("Unknown cargo type: " + cargoName);
}

Called Methods

No outgoing method calls

exitForm

Class: experimental.DialogueBoxTester

Documentation

/** Exit the Application. */

Source Code

/** Exit the Application. */
private void exitForm(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_exitForm
System.exit(0);
}// GEN-LAST:event_exitForm

Called Methods

No outgoing method calls

ItemsTransactionAggregator

Class: jfreerails.world.top.ItemsTransactionAggregator

Documentation

No documentation available

Source Code

public ItemsTransactionAggregator(ReadOnlyWorld w,
FreerailsPrincipal principal) {
super(w, principal);
}

showBrokerScreen

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showBrokerScreen() {
// this is Creating a BrokerScreen Internal Frame in the Main Frame
BrokerScreenHtmlJFrame brokerScreenHtmlJFrame = new BrokerScreenHtmlJFrame();
brokerScreenHtmlJFrame.setup(this.modelRoot, vl,
this.closeCurrentDialogue);
brokerScreenHtmlJFrame.setFrameIcon(null);
showContent(brokerScreenHtmlJFrame);
}

newWorld

Class: jfreerails.launcher.GUIClient

Documentation

No documentation available

Source Code

@Override
protected void newWorld(World w) {
try {
if (null == vl || !vl.validate(w)) {
try {
vl = new RenderersRootImpl(w, monitor);
monitor.finished();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Should be a smarter way of doing this..
for (int player = 0; player < w.getNumberOfPlayers(); player++) {
Player p = w.getPlayer(player);
if (p.getName().equals(this.name)) {
modelRoot.setup(w, p.getPrincipal());
}
}
modelRoot.setProperty(ModelRoot.Property.SERVER, connection2Server
.getServerDetails());
actionRoot.setup(modelRoot, vl);
factory.setup(vl, w);
} catch (Exception e) {
ReportBugTextGenerator.unexpectedException(e);
}
}

improve

Class: jfreerails.controller.FinancialMoveProducer

Documentation

No documentation available

Source Code

EconomicClimate improve() {
return null;
}

Called Methods

No outgoing method calls

refreshTile

Class: jfreerails.client.view.DetailMapRenderer

Documentation

No documentation available

Source Code

public void refreshTile(int x, int y) {
background.refreshTile(x, y);
}

hasNext

Class: jfreerails.world.common.FreerailsPathIterator

Documentation

/**
* Tests whether the path has another segment.
*/

Source Code

/**
* Tests whether the path has another segment.
*/
boolean hasNext();

Called Methods

No outgoing method calls

next

Class: jfreerails.world.top.NonNullElements

Documentation

No documentation available

Source Code

public boolean next() {
int nextIndex = index; // this is used to look ahead.
do {
nextIndex++;
if (nextIndex >= listSize()) {
return false;
}
} while (!testCondition(nextIndex));
row++;
index = nextIndex;
return true;
}

getServerControls

Class: jfreerails.client.view.ActionRoot

Documentation

No documentation available

Source Code

public ServerControlModel getServerControls() {
return serverControls;
}

Called Methods

No outgoing method calls

getProperty

Class: jfreerails.launcher.LauncherInterface

Documentation

No documentation available

Source Code

String getProperty(String key);

Called Methods

No outgoing method calls

getYearAndMonth

Class: jfreerails.world.common.GameCalendar

Documentation

No documentation available

Source Code

public String getYearAndMonth(int i) {
int month = getMonth(i);
String monthAbrev = null;
switch (month) {
case 0: {
monthAbrev = "Jan";
break;
}
case 1: {
monthAbrev = "Feb";
break;
}
case 2: {
monthAbrev = "Mar";
break;
}
case 3: {
monthAbrev = "Apr";
break;
}
case 4: {
monthAbrev = "May";
break;
}
case 5: {
monthAbrev = "Jun";
break;
}
case 6: {
monthAbrev = "Jul";
break;
}
case 7: {
monthAbrev = "Aug";
break;
}
case 8: {
monthAbrev = "Sep";
break;
}
case 9: {
monthAbrev = "Oct";
break;
}
case 10: {
monthAbrev = "Nov";
break;
}
case 11: {
monthAbrev = "Dec";
break;
}
}
return monthAbrev + " " + getYearAsString(i);
}

defensiveCopy

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public World defensiveCopy() {
return (World) Utils.cloneBySerialisation(this);
}

setGameModel

Class: jfreerails.controller.ClientControlInterface

Documentation

/** Called when a new game is started or a game is loaded. */

Source Code

/** Called when a new game is started or a game is loaded. */
void setGameModel(FreerailsMutableSerializable world);

Called Methods

No outgoing method calls

findPosition

Class: jfreerails.controller.TrainAccessor

Documentation

No documentation available

Source Code

public TrainPositionOnMap findPosition(double time) {
ActivityIterator ai = w.getActivities(p, id);
ai.gotoLastActivity();
while (ai.getStartTime() > time && ai.hasPrevious()) {
ai.previousActivity();
}
double dt = time - ai.getStartTime();
dt = Math.min(dt, ai.getDuration());
TrainMotion tm = (TrainMotion) ai.getActivity();
return tm.getState(dt);
}

hashCode

Class: jfreerails.move.MoveStatus

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = (ok ? 1 : 0);
result = 29 * result + (message != null ? message.hashCode() : 0);
return result;
}

Called Methods

No outgoing method calls

refreshTile

Class: jfreerails.client.renderer.TrackLayer

Documentation

No documentation available

Source Code

public void refreshTile(int x, int y) {
}

Called Methods

No outgoing method calls

createBrokerMenu

Class: jfreerails.client.top.GUIComponentFactory

Documentation

No documentation available

Source Code

JMenu createBrokerMenu();

Called Methods

No outgoing method calls

getNewStation

Class: jfreerails.move.AddStationMove

Documentation

No documentation available

Source Code

public StationModel getNewStation() {
AddItemToListMove addStation = (AddItemToListMove) super.getMove(2);
return (StationModel) addStation.getAfter();
}

getH

Class: jfreerails.controller.FlatTrackExplorer

Documentation

No documentation available

Source Code

public int getH() {
// TODO Auto-generated method stub
return 0;
}

Called Methods

No outgoing method calls

parse

Class: jfreerails.server.parser.Track_TilesParser

Documentation

/**
* The recognizer entry method taking an Inputsource.
*
* @param input
* InputSource to be parsed.
* @throws java.io.IOException
* on I/O error.
* @throws SAXException
* propagated exception thrown by a DocumentHandler.
* @throws javax.xml.parsers.ParserConfigurationException
* a parser satisfying requested configuration can not be
* created.
*/

Source Code

/**
* The recognizer entry method taking an Inputsource.
*
* @param input
* InputSource to be parsed.
* @throws java.io.IOException
* on I/O error.
* @throws SAXException
* propagated exception thrown by a DocumentHandler.
* @throws javax.xml.parsers.ParserConfigurationException
* a parser satisfying requested configuration can not be
* created.
*/
public static void parse(final InputSource input,
final Track_TilesHandler handler) throws SAXException,
ParserConfigurationException, IOException {
parse(input, new Track_TilesParser(handler));
}

hashCode

Class: jfreerails.world.terrain.Conversion

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = input;
result = 29 * result + output;
return result;
}

Called Methods

No outgoing method calls

findNextStep

Class: jfreerails.controller.MoveTrainPreMove

Documentation

/** Uses static method to make testing easier.*/

Source Code

/** Uses static method to make testing easier.*/
public static Step findNextStep(ReadOnlyWorld world,
PositionOnTrack currentPosition, ImPoint target) {
PathOnTrackFinder pathFinder = new PathOnTrackFinder(world);
try {
ImPoint location = new ImPoint(currentPosition.getX(),
currentPosition.getY());
pathFinder.setupSearch(location, target);
pathFinder.search(-1);
return pathFinder.pathAsVectors()[0];
} catch (PathNotFoundException e) {
// The pathfinder couldn't find a path so we
// go in any legal direction.
FlatTrackExplorer explorer = new FlatTrackExplorer(world,
currentPosition);
explorer.nextEdge();
int next = explorer.getVertexConnectedByEdge();
PositionOnTrack nextPosition = new PositionOnTrack(next);
return nextPosition.cameFrom();
}
}

isMoving

Class: jfreerails.controller.TrainAccessor

Documentation

No documentation available

Source Code

public boolean isMoving(double time){
TrainMotion tm = findCurrentMotion(time);
double speed = tm.getSpeedAtEnd();
return speed != 0;
}

setTime

Class: jfreerails.world.top.World

Documentation

No documentation available

Source Code

void setTime(GameTime t);

Called Methods

No outgoing method calls

removeLastActivity

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public Activity removeLastActivity(FreerailsPrincipal p, int index) {
int playerIndex = p.getWorldIndex();
if (activityLists.sizeD3(playerIndex, index) < 2)
throw new IllegalStateException();
Activity act = activityLists.removeLastD3(playerIndex, index).act;
return act;
}

testValidation

Class: jfreerails.world.common.PositionOnTrackTest

Documentation

No documentation available

Source Code

public void testValidation() {
assertTrue(PositionOnTrack.MAX_COORDINATE < 70000);
assertTrue(PositionOnTrack.MAX_COORDINATE > 10000);
assertEquals(PositionOnTrack.MAX_DIRECTION, 7);
assertNoException(0, 0, Step.EAST);
assertNoException(PositionOnTrack.MAX_COORDINATE,
PositionOnTrack.MAX_COORDINATE, Step.NORTH_WEST);
assertException(-1, 0, Step.EAST);
assertException(0, -1, Step.EAST);
assertException(PositionOnTrack.MAX_COORDINATE + 1,
PositionOnTrack.MAX_COORDINATE, Step.NORTH_WEST);
assertException(PositionOnTrack.MAX_COORDINATE,
PositionOnTrack.MAX_COORDINATE + 1, Step.NORTH_WEST);
}

getBefore

Class: jfreerails.move.ChangeItemInListMove

Documentation

No documentation available

Source Code

public FreerailsSerializable getBefore() {
return before;
}

Called Methods

No outgoing method calls

finished

Class: jfreerails.util.Unknown

Documentation

No documentation available

Source Code

public void finished() {
}

Called Methods

No outgoing method calls

getSchedule

Class: jfreerails.controller.TrainAccessor

Documentation

No documentation available

Source Code

public ImmutableSchedule getSchedule() {
TrainModel train = getTrain();
return (ImmutableSchedule) w.get(p, KEY.TRAIN_SCHEDULES, train
.getScheduleID());
}

paintTrack

Class: experimental.TrackRenderer

Documentation

No documentation available

Source Code

void paintTrack(Graphics2D g, List<CubicCurve2D.Double> sections) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if (!tunnel) {
// Draw sleepers
g.setColor(sleepersColor);
for (CubicCurve2D.Double section : sections) {
BasicStroke dashed = getStroke4Curve(section);
g.setStroke(dashed);
g.draw(section);
}
g.setColor(railsColor);
} else {
g.setColor(Color.BLACK);
}
// Draw rails
g.setStroke(rail);
for (CubicCurve2D.Double section : sections) {
float halfGauge = gauge / 2;
CubicCurve2D.Double rail1 = createAdjacentCurve(section, halfGauge,
halfGauge);
CubicCurve2D.Double rail2 = createAdjacentCurve(section,
-halfGauge, -halfGauge);
g.draw(rail1);
g.draw(rail2);
}
}

addD2

Class: jfreerails.util.List3D

Documentation

No documentation available

Source Code

int addD2(int d1);

Called Methods

No outgoing method calls

main

Class: experimental.TestLogging

Documentation

No documentation available

Source Code

public static void main(String[] args) {
Logger logger1 = Logger.getLogger(TestLogging.class.getName());
logger1.info("Logging properties file: "
+ System.getProperty("java.util.logging.config.file"));
logger1.severe("Hello severe logging");
logger1.warning("Hello warning logging");
logger1.info("Hello info logging");
logger1.fine("Hello fine logging");
logger1.finer("Hello finer logging");
logger1.finest("Hello finest logging");
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.train.SpeedTimeAndStatus

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof SpeedTimeAndStatus))
return false;
final SpeedTimeAndStatus speedTimeAndStatus = (SpeedTimeAndStatus) o;
if (acceleration != speedTimeAndStatus.acceleration)
return false;
if (dt != speedTimeAndStatus.dt)
return false;
if (s != speedTimeAndStatus.s)
return false;
if (speed != speedTimeAndStatus.speed)
return false;
if (activity != null ? !activity.equals(speedTimeAndStatus.activity)
: speedTimeAndStatus.activity != null)
return false;
return true;
}

Called Methods

No outgoing method calls

propertyChange

Class: jfreerails.client.view.MapViewJComponentConcrete

Documentation

/**
* Checks what triggered the specified PropertyChangeEvent and reacts as
* follows.
* <p>
* (1) If it was ModelRoot.CURSOR_POSITION, scrolls the map if necessary.
* </p>
* <p>
* (2) If it was ModelRoot.QUICK_MESSAGE, display or hide the message as
* appropriate.
* </p>
* <p>
* (3) If it was ModelRoot.PERMANENT_MESSAGE, display or hide the message as
* appropriate.
* </p>
*/

Source Code

/**
* Checks what triggered the specified PropertyChangeEvent and reacts as
* follows.
* <p>
* (1) If it was ModelRoot.CURSOR_POSITION, scrolls the map if necessary.
* </p>
* <p>
* (2) If it was ModelRoot.QUICK_MESSAGE, display or hide the message as
* appropriate.
* </p>
* <p>
* (3) If it was ModelRoot.PERMANENT_MESSAGE, display or hide the message as
* appropriate.
* </p>
*/
public void propertyChange(ModelRoot.Property p, Object before, Object after) {
if (p.equals(ModelRoot.Property.CURSOR_POSITION)) {
ImPoint newPoint = (ImPoint) after;
ImPoint oldPoint = (ImPoint) before;
if (null == oldPoint) {
oldPoint = new ImPoint();
}
react2cursorMove(newPoint, oldPoint);
} else if (p.equals(ModelRoot.Property.QUICK_MESSAGE)) {
String newMessage = (String) after;
if (null != newMessage) {
println(newMessage);
} else {
// Its null, so stop displaying whatever we where displaying.
displayMessageUntil = Long.MIN_VALUE;
}
} else if (p.equals(ModelRoot.Property.PERMANENT_MESSAGE)) {
message = (String) after;
}
}

getAppropriateTrackRule

Class: jfreerails.controller.BuildTrackExplorer

Documentation

No documentation available

Source Code

private TrackRule getAppropriateTrackRule(int x, int y) {
final FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
TrackRule rule;
if (!tile.hasTrack()) {
int terrainTypeID = tile.getTerrainTypeID();
int trackRuleID = buildTrackStrategy.getRule(terrainTypeID);
if (trackRuleID == -1) {
return null; // Can't build on this terrain!
}
rule = (TrackRule) world.get(SKEY.TRACK_RULES, trackRuleID);
} else {
rule = tile.getTrackPiece().getTrackRule();
}
return rule;
}

getDefaultIcon

Class: jfreerails.client.renderer.AbstractTileRenderer

Documentation

No documentation available

Source Code

public Image getDefaultIcon() {
return getTileIcons()[0];
}

canIssueBond

Class: jfreerails.controller.FinancialDataGatherer

Documentation

No documentation available

Source Code

public boolean canIssueBond() {
return nextBondInterestRate() <= 7;
}

setupSearch

Class: jfreerails.controller.TrackPathFinder

Documentation

No documentation available

Source Code

public void setupSearch(ImPoint startPoint, ImPoint targetPoint,
BuildTrackStrategy bts) throws PathNotFoundException {
logger
.fine("Find track path from " + startPoint + " to "
+ targetPoint);
this.startPoint = startPoint;
int[] targetInts = findTargets(targetPoint);
int[] startInts = findTargets(startPoint);
BuildTrackExplorer explorer = new BuildTrackExplorer(world,
principal, startPoint, targetPoint);
explorer.setBuildTrackStrategy(bts);
pathFinder.setupSearch(startInts, targetInts, explorer);
}

paintTile

Class: jfreerails.client.renderer.MapBackgroundRender

Documentation

No documentation available

Source Code

public void paintTile(Graphics g, int x, int y) {
terrainLayer.paintTile(g, x, y);
trackLayer.paintTile(g, x, y);
cityNames.paint((Graphics2D) g);
stationNames.paint((Graphics2D) g);
}

Called Methods

  • jfreerails.client.renderer.MapBackgroundRender.TrackLayer.paintTile (external)
  • jfreerails.client.common.Painter.paint
  • jfreerails.client.renderer.MapBackgroundRender.TerrainLayer.paintTile (external)

end_ListOfLegalRoutesAcrossNode

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void end_ListOfLegalRoutesAcrossNode() throws SAXException {
}

Called Methods

No outgoing method calls

nextSegment

Class: jfreerails.world.train.PathWalkerImpl

Documentation

No documentation available

Source Code

public void nextSegment(IntLine line) {
if (!hasNext()) {
throw new NoSuchElementException();
}
// If we are at the end of the current segment, start a new one.
if (currentSegment.getLength() <= distanceAlongCurrentSegment) {
startNewSegment(line);
} else {
startInMiddleOfSegment(line);
}
double remainingDistanceAlongCurrentSegment = currentSegment
.getLength()
- distanceAlongCurrentSegment;
if (distanceOfThisStepRemaining > remainingDistanceAlongCurrentSegment) {
endAtSegmentEnd(line, remainingDistanceAlongCurrentSegment);
} else {
endInMiddleOfSegment(line);
}
/*
* Sanity check: the first point of the last line should equal the
* second point of the current line.
*
*/
if (!beforeFirst) {
if (line.x1 != this.lastX) {
throw new IllegalStateException();
}
if (line.y1 != this.lastY) {
throw new IllegalStateException();
}
}
this.lastX = line.x2;
this.lastY = line.y2;
beforeFirst = false;
return;
}

tryDoMove

Class: jfreerails.move.RemoveItemFromListMove

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.size(principal, listKey) < (index + 1)) {
return MoveStatus.moveFailed("w.size(listKey)="
+ w.size(principal, listKey) + " but index =" + index);
}
FreerailsSerializable item2remove = w.get(principal, listKey, index);
if (null == item2remove) {
return MoveStatus.moveFailed("The item at position " + index
+ " has already been removed.");
}
if (!item.equals(item2remove)) {
String reason = "The item at position " + index + " in the list ("
+ item2remove.toString() + ") is not the expected item ("
+ item.toString() + ").";
return MoveStatus.moveFailed(reason);
}
return MoveStatus.MOVE_OK;
}

getEngineType

Class: jfreerails.client.view.SelectEngineJPanel

Documentation

/**
* Returns the number of the currently selected engine type.
*
*/

Source Code

/**
* Returns the number of the currently selected engine type.
*
*/
public int getEngineType() {
return jList1.getSelectedIndex();
}

Called Methods

No outgoing method calls

main

Class: jfreerails.client.view.ShowJavaProperties

Documentation

No documentation available

Source Code

public static void main(String[] args) {
logger.info(getPropertiesHtmlString());
}

getBuildMode

Class: jfreerails.controller.TrackMoveProducer

Documentation

No documentation available

Source Code

public BuildMode getBuildMode() {
return (BuildMode) mr.getProperty(Property.TRACK_BUILDER_MODE);
}

mousePressed

Class: jfreerails.client.view.MapViewJComponentMouseAdapter

Documentation

No documentation available

Source Code

@Override
public void mousePressed(MouseEvent evt) {
/*
* Note, moving the cursor using the mouse is now handled in
* UserInputOnMapController
*/
if (SwingUtilities.isRightMouseButton(evt)) {
MapViewJComponentConcrete.this
.setCursor(Cursor
.getPredefinedCursor((LINEAR_ACCEL > 0) ? Cursor.HAND_CURSOR
: Cursor.MOVE_CURSOR));
lastMouseLocation.x = evt.getX();
lastMouseLocation.y = evt.getY();
screenLocation.x = evt.getX();
screenLocation.y = evt.getY();
sigmadelta.x = 0;
sigmadelta.y = 0;
javax.swing.SwingUtilities.convertPointToScreen(screenLocation,
MapViewJComponentConcrete.this);
}
}

Called Methods

No outgoing method calls

setUp

Class: jfreerails.client.view.BalanceSheetGeneratorTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
world = new WorldImpl(10, 10);
player = new Player("Player X", world.getNumberOfPlayers());
world.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
world.setTime(new GameTime(0));
Move addPlayerMove = AddPlayerMove.generateMove(world, player);
MoveStatus ms = addPlayerMove.doMove(world, player.getPrincipal());
assertTrue(ms.message, ms.ok);
world.setTime(new GameTime(100));
}

testMove

Class: jfreerails.controller.MoveTrainPreMove1stTest

Documentation

No documentation available

Source Code

@Override
public void testMove() {
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
Move m = preMove.generateMove(world);
assertNotNull(m);
assertSurvivesSerialisation(m);
}

PlayerPrincipal

Class: jfreerails.world.player.PlayerPrincipal

Documentation

No documentation available

Source Code

public PlayerPrincipal(int id, String name) {
super(id);
this.id = id;
this.name = name;
}

DisplayModesComboBoxModels

Class: jfreerails.client.view.DisplayModesComboBoxModels

Documentation

No documentation available

Source Code

public DisplayModesComboBoxModels() {
DisplayMode currentMode = defaultConfiguration.getDevice()
.getDisplayMode();
selection = new MyDisplayMode(currentMode);
DisplayMode[] displayModes = defaultConfiguration.getDevice()
.getDisplayModes();
for (int i = 0; i < displayModes.length; i++) {
MyDisplayMode mode = new MyDisplayMode(displayModes[i]);
modes.add(mode);
}
}

Called Methods

No outgoing method calls

update

Class: jfreerails.client.renderer.BuildTrackController

Documentation

No documentation available

Source Code

public void update() {
// update search for path if necessary.
if (searchStatus() == IncrementalPathFinder.SEARCH_PAUSED) {
updateSearch();
}
}

getIcon

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

No documentation available

Source Code

private ImageIcon getIcon(String typeName) {
try {
String relativeFileName = "icons" + File.separator + typeName
+ ".png";
relativeFileName = relativeFileName.replace(' ', '_');
Image im = imageManager.getImage(relativeFileName);
return new ImageIcon(im);
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException(e);
}
}

hashCode

Class: jfreerails.world.accounts.EconomicClimate

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = (name != null ? name.hashCode() : 0);
result = 29 * result + baseInterestRate;
return result;
}

Called Methods

No outgoing method calls

HtmlJPanel

Class: jfreerails.client.view.HtmlJPanel

Documentation

No documentation available

Source Code

public HtmlJPanel(URL url) {
initComponents();
setHtml(loadText(url));
}

addActiveEntity

Class: jfreerails.world.top.World

Documentation

No documentation available

Source Code

int addActiveEntity(FreerailsPrincipal principal, Activity element);

Called Methods

No outgoing method calls

checkValidity

Class: jfreerails.world.common.Step

Documentation

/**
* Returns true if the values passed could be used to create a valid vector.
*/

Source Code

/**
* Returns true if the values passed could be used to create a valid vector.
*/
public static boolean checkValidity(int x, int y) {
if ((((x < -1) || (x > 1)) || ((y < -1) || (y > 1)))
|| ((x == 0) && (y == 0))) {
return false;
}
return true;
}

Called Methods

No outgoing method calls

assertDoMoveFails

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

protected void assertDoMoveFails(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.doMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertTrue("Move went through when it should have failed", !ms.ok);
}

testEquals2

Class: jfreerails.world.top.WorldImplTest

Documentation

No documentation available

Source Code

public void testEquals2() {
World original;
World copy, copy2;
original = new WorldImpl();
copy = original.defensiveCopy();
copy2 = original.defensiveCopy();
// Test adding players.
Player a = new Player("Fred");
Player b = new Player("John");
original.addPlayer(a);
copy.addPlayer(b);
assertFalse(copy.equals(original));
copy.removeLastPlayer();
assertTrue(copy2.equals(copy));
copy.addPlayer(a);
assertTrue(copy.equals(original));
}

assertBundlesEqual

Class: jfreerails.world.cargo.CargoBundleTest

Documentation

No documentation available

Source Code

private void assertBundlesEqual(MutableCargoBundle a, MutableCargoBundle b) {
assertEquals(a, b);
assertEquals(a, a);
assertEquals(b, a);
ImmutableCargoBundle immA = a.toImmutableCargoBundle();
assertEquals(immA, immA);
assertEquals(immA, b);
ImmutableCargoBundle immB = b.toImmutableCargoBundle();
assertEquals(immA, immB);
Serializable cloneA = Utils.cloneBySerialisation(immA);
Serializable cloneB = Utils.cloneBySerialisation(immB);
assertEquals(cloneA, cloneB);
assertEquals(a, immB);
}

shutdownInput

Class: jfreerails.network.InetConnection

Documentation

No documentation available

Source Code

synchronized void shutdownInput() throws IOException {
socket.shutdownInput();
if (socket.isInputShutdown() && socket.isOutputShutdown()) {
socket.close();
}
}

Called Methods

No outgoing method calls

calcT

Class: jfreerails.world.train.ConstAcc

Documentation

No documentation available

Source Code

public double calcT(double s) {
if(s == finalS ) return finalT;
if(s < 0 || s > this.finalS )
throw new IllegalArgumentException(s+" < 0 || "+s+" > "+finalS );
double returnValue = calcT(u, a, s);
returnValue = Math.min(returnValue, finalT);
return returnValue;
}

paintComponent

Class: jfreerails.client.view.MapViewJComponentConcrete

Documentation

No documentation available

Source Code

@Override
protected void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);
if (null != mapCursor && this.isFocusOwner()) {
mapCursor.paintCursor(g, new java.awt.Dimension(30, 30));
}
if (System.currentTimeMillis() < this.displayMessageUntil) {
Rectangle visRect = this.getVisibleRect();
g.setColor(Color.WHITE);
g.setFont(USER_MESSAGE_FONT);
for (int i = 0; i < userMessage.length; i++) {
g.drawString(this.userMessage[i], 50 + visRect.x, 50
+ visRect.y + i * 20);
}
}
if (message != null) {
Rectangle visRect = this.getVisibleRect();
g.setColor(Color.lightGray);
g.setFont(LARGE_MESSAGE_FONT);
int msgWidth = g.getFontMetrics(LARGE_MESSAGE_FONT).stringWidth(
message);
int msgHeight = g.getFontMetrics(LARGE_MESSAGE_FONT).getHeight();
g.drawString(message,
(int) (visRect.x + (visRect.getWidth() - msgWidth) / 2),
(int) (visRect.y + (visRect.getHeight() - msgHeight) / 2));
}
}

canBuildOnThisTerrainType

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

public boolean canBuildOnThisTerrainType(TerrainType.Category TerrainType) {
return true; // No track is possible anywhere.
}

Called Methods

No outgoing method calls

getTime

Class: jfreerails.network.specifics.MovePrecommitterTest

Documentation

No documentation available

Source Code

private GameTime getTime() {
return w.currentTime();
}

getFlatInstance

Class: jfreerails.world.track.TrackConfiguration

Documentation

No documentation available

Source Code

public static TrackConfiguration getFlatInstance(Step v) {
return from9bitTemplate(v.get9bitTemplate());
}

NonNullElements

Class: jfreerails.world.top.NonNullElements

Documentation

No documentation available

Source Code

public NonNullElements(KEY k, ReadOnlyWorld world, FreerailsPrincipal p) {
key = k;
w = world;
principal = p;
skey = null;
if (null == k) {
throw new NullPointerException();
}
if (null == world) {
throw new NullPointerException();
}
if (null == p) {
throw new NullPointerException();
}
}

Called Methods

No outgoing method calls

getListCellRendererComponent

Class: jfreerails.client.view.TrainCellRenderer

Documentation

No documentation available

Source Code

public Component getListCellRendererComponent(JList list, Object value,
/* value to display */
int index, /* cell index */
boolean isSelected, /* is the cell selected */
boolean cellHasFocus) /* the list and the cell have the focus */{
EngineType engine = (EngineType) value;
label.setFont(new java.awt.Font("Dialog", 0, 12));
String text = "<html><body>" + (isSelected ? "<strong>" : "")
+ engine.getEngineTypeName() + "<br>"
+ engine.getMaxSpeed() + " m.p.h. "
+ engine.getPowerAtDrawbar() + " hp $"
+ engine.getPrice().toString()
+ (isSelected ? "</strong>" : "") + "</body></html>";
label.setText(text);
Image image = rr.getEngineImages(index).getSideOnImage();
int height = image.getHeight(null);
int width = image.getWidth(null);
int scale = height / 50;
ImageIcon icon = new ImageIcon(image.getScaledInstance(width
/ scale, height / scale, Image.SCALE_FAST));
label.setIcon(icon);
return label;
}

getInstanceMappedToKey

Class: jfreerails.client.view.KeyCode2OneTileMoveVector

Documentation

/** Returns the OneTileMoveVector that is mapped to the specified keycode. */

Source Code

/** Returns the OneTileMoveVector that is mapped to the specified keycode. */
public static Step getInstanceMappedToKey(int keycode)
throws NoSuchElementException {
Integer integer = new Integer(keycode);
if (!keycode2vector.containsKey(integer)) {
throw new NoSuchElementException(String.valueOf(keycode));
}
return keycode2vector.get(integer);
}

Called Methods

No outgoing method calls

getRemoteServerAddress

Class: jfreerails.launcher.ClientOptionsJPanel

Documentation

No documentation available

Source Code

InetSocketAddress getRemoteServerAddress() {
String portStr = remotePort.getText();
if (portStr == null) {
return null;
}
int port;
try {
port = Integer.parseInt(portStr);
} catch (NumberFormatException e) {
return null;
}
InetSocketAddress address;
try {
address = new InetSocketAddress(remoteIP.getText(), port);
} catch (IllegalArgumentException e) {
return null;
}
/*
* cut and pasted InetSocketAddress isa = getRemoteServerAddress(); if
* (isa == null) { infoText = "Please enter a valid remote server
* address"; } else if (isa.isUnresolved()) { infoText = "Couldn't
* resolve remote server address"; } else { isValid = true; }
*/
return address;
}

Called Methods

No outgoing method calls

createWorldFromMapFile

Class: jfreerails.server.OldWorldImpl

Documentation

/** Note, the map name is converted to lower case and any spaces
* are replaced with underscores.
*
*/

Source Code

/** Note, the map name is converted to lower case and any spaces
* are replaced with underscores.
*
*/
public static World createWorldFromMapFile(String mapName,
FreerailsProgressMonitor pm) {
mapName = mapName.toLowerCase();
mapName = mapName.replace(' ', '_');
pm.setValue(0);
pm.nextStep(7);
int progress = 0;
TileSetFactory tileFactory = new TileSetFactoryImpl();
pm.setValue(++progress);
WorldImpl w = new WorldImpl();
pm.setValue(++progress);
WagonAndEngineTypesFactory wetf = new WagonAndEngineTypesFactory();
pm.setValue(++progress);
wetf.addTypesToWorld(w);
pm.setValue(++progress);
tileFactory.addTerrainTileTypesList(w);
pm.setValue(++progress);
URL track_xml_url = OldWorldImpl.class
.getResource("/jfreerails/data/track_tiles.xml");
Track_TilesHandlerImpl trackSetFactory = new Track_TilesHandlerImpl(
track_xml_url);
pm.setValue(++progress);
trackSetFactory.addTrackRules(w);
pm.setValue(++progress);
// Load the terrain map
URL map_url = OldWorldImpl.class.getResource("/jfreerails/data/"
+ mapName + ".png");
MapFactory.setupMap(map_url, w, pm);
// Load the city names
URL cities_xml_url = OldWorldImpl.class.getResource("/jfreerails/data/"
+ mapName + "_cities.xml");
try {
InputCityNames.readCityNames(w, cities_xml_url);
} catch (SAXException e) {
}
// Randomly position the city tiles
CityTilePositioner ctp = new CityTilePositioner(w);
ctp.initCities();
// Set the time..
w.set(ITEM.CALENDAR, new GameCalendar(1200, 1840));
w.setTime(new GameTime(0));
w.set(ITEM.GAME_SPEED, new GameSpeed(10));
w.set(ITEM.GAME_RULES, GameRules.DEFAULT_RULES);
/*
* Note, money used to get added to player accounts here, now it is done
* when players are added. See AddPlayerMove
*/
return w;
}

path

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public FreerailsPathIterator path() {
return new SimplePathIteratorImpl(this.xpoints, this.ypoints);
}

Called Methods

No outgoing method calls

getPreferredScrollableViewportSize

Class: jfreerails.client.view.MapViewJComponent

Documentation

/**
* Gets the preferredScrollableViewportSize attribute of the
* MapViewJComponent object.
*
* @return The preferredScrollableViewportSize value
*/

Source Code

/**
* Gets the preferredScrollableViewportSize attribute of the
* MapViewJComponent object.
*
* @return The preferredScrollableViewportSize value
*/
public java.awt.Dimension getPreferredScrollableViewportSize() {
return this.getPreferredSize();
}

paintRect

Class: jfreerails.client.renderer.MapBackgroundRender

Documentation

No documentation available

Source Code

public void paintRect(Graphics g, Rectangle visibleRect) {
int tileWidth = 30;
int tileHeight = 30;
clipRectangle = g.getClipBounds(clipRectangle);
int x = clipRectangle.x / tileWidth;
int y = clipRectangle.y / tileHeight;
int width = (clipRectangle.width / tileWidth) + 2;
int height = (clipRectangle.height) / tileHeight + 2;
paintRectangleOfTiles(g, x, y, width, height);
cityNames.paint((Graphics2D) g);
stationNames.paint((Graphics2D) g);
}

getMapNames

Class: jfreerails.network.specifics.NewGameMessage2Server

Documentation

/**
* TODO This would be better implemented in a config file, or better still
* dynamically determined by scanning the directory.
*/

Source Code

/**
* TODO This would be better implemented in a config file, or better still
* dynamically determined by scanning the directory.
*/
public static String[] getMapNames() {
return new String[] { "South America", "Small South America" };
}

Called Methods

No outgoing method calls

generateFileNameNumber

Class: jfreerails.client.renderer.RiverStyleTileRenderer

Documentation

No documentation available

Source Code

@Override
protected String generateFileNameNumber(int i) {
return BinaryNumberFormatter.formatWithLowBitOnLeft(i, 4);
}

size

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public int size(FreerailsPrincipal p, KEY key) {
int playerIndex = p.getWorldIndex();
return lists.sizeD3(playerIndex, key.getKeyID());
}

assertRemoveTrackSucceeds

Class: jfreerails.move.ChangeTrackPieceCompositeMoveTest

Documentation

No documentation available

Source Code

private void assertRemoveTrackSucceeds(ImPoint p, Step v) {
try {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateRemoveTrackMove(p, v, getWorld(),
MapFixtureFactory.TEST_PRINCIPAL);
MoveStatus status = move.doMove(getWorld(), Player.AUTHORITATIVE);
assertEquals(true, status.isOk());
} catch (Exception e) {
fail();
}
}

testAddD2

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List2DDiff.addD2(int, T)'
*/
public void testAddD2() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
assertEquals(2, diffs.sizeD2(0));
int i = diffs.addD2(0, String.valueOf(3));
assertEquals(2, i);
assertEquals(3, diffs.sizeD2(0));
i = diffs.addD2(0, String.valueOf(4));
assertEquals(3, i);
assertEquals(4, diffs.sizeD2(0));
assertEquals(String.valueOf(3), diffs.get(0, 2));
assertEquals(String.valueOf(4), diffs.get(0, 3));
}

setPosition

Class: jfreerails.controller.GraphExplorer

Documentation

No documentation available

Source Code

void setPosition(int vertex);

Called Methods

No outgoing method calls

setUp

Class: jfreerails.controller.TrackPathFinderTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
world = new WorldImpl(20, 20);
world.addPlayer(testPlayer);
world.set(ITEM.GAME_RULES, GameRules.NO_RESTRICTIONS);
MapFixtureFactory.generateTrackRuleList(world);
}

get9bitTemplate

Class: jfreerails.world.track.TrackConfiguration

Documentation

/**
* @return an int representing this track configuration.
*/

Source Code

/**
* @return an int representing this track configuration.
*/
public int get9bitTemplate() {
return configuration;
}

Called Methods

No outgoing method calls

updateFPSCounter

Class: jfreerails.client.top.FPScounter

Documentation

No documentation available

Source Code

// Display the average number of FPS.
void updateFPSCounter() {
long currentTime = System.nanoTime();
if (newFrameCount == 0) {
lastFrameTime = currentTime;
}
double dt = currentTime - lastFrameTime;
double fps = 1000000000d / dt;
fpsValues[newFrameCount % fpsValues.length] = fps;
newFrameCount++;
int n = fpsValues.length;
if (newFrameCount > fpsValues.length) {
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
double mean = 0;
for (int i = 0; i < fpsValues.length; i++) {
min = Math.min(min, fpsValues[i]);
max = Math.max(max, fpsValues[i]);
mean += fpsValues[i];
}
mean = mean / n;
if (mean > max)
throw new IllegalStateException();
if (mean < min)
throw new IllegalStateException();
double variance = 0;
for (int i = 0; i < fpsValues.length; i++) {
double xMinusU = fpsValues[i] - mean;
variance += xMinusU * xMinusU;
}
variance = variance / n;
if (newFrameCount % 20 == 0) {
StringBuffer sb = new StringBuffer();
sb.append("FPS\n");
sb.append(" n ");
sb.append(n);
sb.append('\n');
sb.append(" \u03BC ");
sb.append(Math.round(mean));
sb.append('\n');
sb.append(" \u03C3 ");
sb.append(Math.round(Math.sqrt(variance)));
sb.append('\n');
sb.append(" min ");
sb.append(Math.round(min));
sb.append('\n');
sb.append(" max ");
sb.append(Math.round(max));
sb.append('\n');
newFPSstr = sb.toString();
}
}
// g.setColor(Color.WHITE);
// g.fillRect(50, 50, 50, 20);
// g.setColor(Color.BLACK);
// g.drawString(newFPSstr, 50, 65);
lastFrameTime = currentTime;
}

Called Methods

No outgoing method calls

getElement

Class: jfreerails.world.top.WorldIterator

Documentation

/** Returns the element the cursor is pointing to. */

Source Code

/** Returns the element the cursor is pointing to. */
FreerailsSerializable getElement();

Called Methods

No outgoing method calls

hasNextEdge

Class: jfreerails.controller.FlatTrackExplorer

Documentation

No documentation available

Source Code

public boolean hasNextEdge() {
if (beforeFirst) {
// We can always go back the way we have come, so if we are before
// the first
// branch, there must be a branch: the one we used to get here.
return true;
}
// Since we can always go back the way we have come, if the direction of
// current branch is not equal to the opposite of the current direction,
// there must be another branch.
Step currentBranchDirection = this.currentBranch.cameFrom();
Step oppositeToCurrentDirection = this.currentPosition.cameFrom()
.getOpposite();
if (oppositeToCurrentDirection.getID() == currentBranchDirection
.getID()) {
return false;
}
return true;
}

isTrainMoving

Class: jfreerails.server.TrainPathFinder

Documentation

No documentation available

Source Code

boolean isTrainMoving() {
boolean moving = stopsHandler.isTrainMoving();
mr.processMove(stopsHandler.getMoves());
return moving;
}

tryDoMove

Class: jfreerails.client.common.Unknown

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(Move move) {
return MoveStatus.moveFailed("No move receiver set on model root!");
}

StationPlacementCursor

Class: jfreerails.client.view.StationPlacementCursor

Documentation

No documentation available

Source Code

private StationPlacementCursor(ActionRoot actionRoot,
StationRadiusRenderer srr, MapViewJComponent mapView) {
scale = mapView.getScale();
this.mapView = mapView;
stationBuildModel = actionRoot.getStationBuildModel();
stationRadiusRenderer = srr;
buildEnabled = stationBuildModel.getStationBuildAction().isEnabled();
}

addTransactions

Class: jfreerails.move.TrackMoveTransactionsGenerator

Documentation

No documentation available

Source Code

public CompositeMove addTransactions(Move move) {
int numberOfTrackTypes = w.size(SKEY.TRACK_RULES);
trackAdded = new int[numberOfTrackTypes];
trackRemoved = new int[numberOfTrackTypes];
fixedCostsStations = 0;
fixedCostsBridges = 0;
unpackMove(move);
generateTransactions();
int numberOfMoves = 1 + transactions.size();
Move[] moves = new Move[numberOfMoves];
moves[0] = move;
for (int i = 0; i < transactions.size(); i++) {
Transaction t = transactions.get(i);
moves[i + 1] = new AddTransactionMove(principal, t, true);
}
return new CompositeMove(moves);
}

equals

Class: jfreerails.util.Lists

Documentation

No documentation available

Source Code

@SuppressWarnings("unchecked")
public static boolean equals(List1D a, List1D b) {
if (a.size() != b.size())
return false;
for (int i = 0; i < a.size(); i++) {
if (!Utils.equal(a.get(i), b.get(i)))
return false;
}
return true;
}

GameTime

Class: jfreerails.world.common.GameTime

Documentation

No documentation available

Source Code

public GameTime(int l) {
this.ticks = l;
}

Called Methods

No outgoing method calls

update

Class: jfreerails.client.common.SoundManager

Documentation

No documentation available

Source Code

public void update(LineEvent event) {
// TODO free up resources when we have finished playing a clip.
}

Called Methods

No outgoing method calls

addPlayer

Class: jfreerails.world.top.World

Documentation

No documentation available

Source Code

int addPlayer(Player player);

Called Methods

No outgoing method calls

createHelpMenu

Class: jfreerails.client.top.GUIComponentFactory

Documentation

No documentation available

Source Code

JMenu createHelpMenu();

Called Methods

No outgoing method calls

getVertexConnectedByEdge

Class: jfreerails.controller.Map

Documentation

No documentation available

Source Code

public int getVertexConnectedByEdge() {
return nodes[position].edges[branch];
}

Called Methods

No outgoing method calls

TrackRuleProperties

Class: jfreerails.world.track.TrackRuleProperties

Documentation

No documentation available

Source Code

public TrackRuleProperties(int rgb, boolean doubleTrack, String name,
TrackRule.TrackCategories c, int radius, int price,
int maintenance, int fixedCost) {
stationRadius = radius;
rGBvalue = rgb;
enableDoubleTrack = doubleTrack;
typeName = name;
category = c;
this.price = new Money(price);
this.maintenanceCost = new Money(maintenance);
this.fixedCost = new Money(fixedCost);
}

Called Methods

No outgoing method calls

getStationToGoto

Class: jfreerails.world.train.Schedule

Documentation

/**
* Returns the station number of the next station the train is scheduled to
* stop at.
*/

Source Code

/**
* Returns the station number of the next station the train is scheduled to
* stop at.
*/
int getStationToGoto();

Called Methods

No outgoing method calls

getTransaction

Class: jfreerails.move.AddTransactionMove

Documentation

No documentation available

Source Code

public Transaction getTransaction() {
return transaction;
}

Called Methods

No outgoing method calls

drawTrackPieceIcon

Class: experimental.LineDrawTrackPieceView

Documentation

No documentation available

Source Code

public void drawTrackPieceIcon(int trackTemplate, java.awt.Graphics g,
int x, int y, java.awt.Dimension tileSize) {
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new java.awt.BasicStroke(8.0f));
g2.setColor(java.awt.Color.red);
if (0 != trackTemplate) {
int drawX = x * tileSize.width;
int drawY = y * tileSize.height;
// g.drawLine(drawX-10,drawY-10,drawX+10,drawY+10);
for (int i = 0; i < 9; i++) {
if ((trackTemplate & (1 << i)) == (1 << i)) {
g2.drawLine(drawX + 15, drawY + 15,
drawX + 15 + 15 * xx[i], drawY + 15 + 15 * yy[i]);
}
}
}
}

Called Methods

No outgoing method calls

showAbout

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showAbout() {
showContent(this.about);
}

calcV

Class: jfreerails.world.train.CompositeSpeedAgainstTime

Documentation

No documentation available

Source Code

public double calcV(double t) {
checkT(t);
TandI tai = getIndex(t);
SpeedAgainstTime acc = values.get(tai.i);
return acc.calcV(tai.offset);
}

checkFields

Class: experimental.CheckFreerailsSerializableClasses

Documentation

No documentation available

Source Code

static boolean checkFields(Class<?> clazz) {
Field[] fields = clazz.getDeclaredFields();
boolean okSoFar = true;
boolean assertImmutable = clazz.isAnnotationPresent(Immutable.class);
for (Field field : fields) {
int modifiers = field.getModifiers();
if (Modifier.isStatic(modifiers)) {
logger.fine("Skipping static field " + field.getName());
continue;
}
Class<?> type = field.getType();
if (type.isPrimitive()) {
continue;
}
// if(!Modifier.isPrivate(modifiers)){
// System.err.println(clazz.getName()+field.getName()+" should be
// private!");
// okSoFar = false;
// }
if (!FreerailsSerializable.class.isAssignableFrom(type)
&& !assertImmutable) {
if (!immutableTypes.contains(type) && !type.isEnum()
&& !type.isAnnotationPresent(Immutable.class)) {
System.err.println(clazz.getName() + "." + field.getName()
+ " {" + type.getName()
+ "} might not be immutable!");
okSoFar = false;
if (!type.isArray())
mutableTypes.add(type);
}
}
}
return okSoFar;
}

Called Methods

No outgoing method calls

generateFilename

Class: jfreerails.client.renderer.TrackPieceRendererImpl

Documentation

No documentation available

Source Code

public static String generateFilename(int i, String trackTypeName) {
String relativeFileNameBase = "track" + File.separator + trackTypeName;
int newTemplate = TrackConfiguration.from9bitTemplate(i)
.get8bitTemplate();
String fileName = relativeFileNameBase + "_"
+ BinaryNumberFormatter.formatWithLowBitOnLeft(newTemplate, 8)
+ ".png";
return fileName;
}

handle_TerrainType

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void handle_TerrainType(final Attributes meta) throws SAXException {
TerrainType.Category cat = TerrainType.Category.valueOf(meta
.getValue("name"));
terrainTypes.add(cat);
}

Called Methods

  • jfreerails.world.terrain.TerrainType.Category.valueOf (external)

toString

Class: jfreerails.world.cargo.ImmutableCargoBundle

Documentation

No documentation available

Source Code

@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("CargoBundle {\n");
for (int i = 0; i < batches.size(); i++) {
sb.append(amounts.get(i));
sb.append(" units of cargo type ");
sb.append(batches.get(i));
sb.append("\n");
}
sb.append("}");
return sb.toString();
}

FreerailsPrincipal

Class: jfreerails.world.player.FreerailsPrincipal

Documentation

No documentation available

Source Code

public FreerailsPrincipal(int worldIndex) {
this.worldIndex = worldIndex;
}

Called Methods

No outgoing method calls

assertTrackHere

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

protected void assertTrackHere(PathOnTiles path) {
ImPoint start = path.getStart();
int x = start.x;
int y = start.y;
for (int i = 0; i < path.steps(); i++) {
assertTrackHere(x, y);
Step step = path.getStep(i);
x += step.deltaX;
y += step.deltaY;
assertTrackHere(x, y);
}
}

testTreasuryStock

Class: jfreerails.controller.FinancialDataGathererTest

Documentation

No documentation available

Source Code

public void testTreasuryStock() {
FreerailsPrincipal principal = player.getPrincipal();
FinancialDataGatherer fdg = new FinancialDataGatherer(w, principal);
assertEquals(0, fdg.treasuryStock());
int treasuryStock = 10000;
int totalStock = FinancialMoveProducer.IPO_SIZE;
int publicStock = totalStock - treasuryStock;
Transaction t = StockTransaction.buyOrSellStock(0, treasuryStock, new Money(5));
w.addTransaction(principal, t);
fdg = new FinancialDataGatherer(w, principal);
assertEquals(treasuryStock,
fdg.treasuryStock());
assertEquals(totalStock,
fdg.totalShares());
assertEquals(publicStock,
fdg.sharesHeldByPublic());
}

cloneBySerialisation

Class: jfreerails.util.Utils

Documentation

No documentation available

Source Code

public static Serializable cloneBySerialisation(Serializable m) {
try {
byte[] bytes = write2ByteArray(m);
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
ObjectInputStream objectIn = new ObjectInputStream(in);
Serializable o;
o = (Serializable) objectIn.readObject();
return o;
} catch (ClassNotFoundException e) {
// Should never happen.
throw new IllegalStateException();
} catch (IOException e) {
// Should never happen.
e.printStackTrace();
throw new IllegalStateException();
}
}

TrackConfiguration

Class: jfreerails.world.track.TrackConfiguration

Documentation

No documentation available

Source Code

private TrackConfiguration(int configuration) {
this.configuration = configuration;
// Calculate length.
int tempLength = 0;
Step[] vectors = Step.getList();
for (int i = 0; i < vectors.length; i++) {
if (this.contains(vectors[i].get9bitTemplate())) {
tempLength += vectors[i].getLength();
}
}
length = tempLength;
}

getTrackTypeID

Class: jfreerails.world.track.TrackPiece

Documentation

No documentation available

Source Code

int getTrackTypeID();

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.train.ConstAcc

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ConstAcc))
return false;
final ConstAcc constAcc = (ConstAcc) o;
if (a != constAcc.a)
return false;
if (finalT != constAcc.finalT)
return false;
if (u != constAcc.u)
return false;
return true;
}

Called Methods

No outgoing method calls

initComponents

Class: jfreerails.launcher.Launcher

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
jPanel1 = new javax.swing.JPanel();
nextButton = new javax.swing.JButton();
prevButton = new javax.swing.JButton();
infoLabel = new javax.swing.JLabel();
getContentPane().setLayout(new java.awt.GridBagLayout());
setTitle("Freerails Launcher");
addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent evt) {
exitForm(evt);
}
});
jPanel1.setLayout(new java.awt.CardLayout());
jPanel1.setPreferredSize(new java.awt.Dimension(400, 300));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
getContentPane().add(jPanel1, gridBagConstraints);
nextButton.setText("Next...");
nextButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nextButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(nextButton, gridBagConstraints);
prevButton.setText("Back...");
prevButton.setEnabled(false);
prevButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
prevButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(prevButton, gridBagConstraints);
infoLabel.setText("Error messages go here!");
infoLabel.setVerticalAlignment(javax.swing.SwingConstants.TOP);
infoLabel.setMinimumSize(new java.awt.Dimension(20, 20));
infoLabel.setPreferredSize(new java.awt.Dimension(20, 20));
infoLabel.setVerifyInputWhenFocusTarget(false);
infoLabel.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(infoLabel, gridBagConstraints);
pack();
}// GEN-END:initComponents

stop

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public void stop() {
// TODO Auto-generated method stub
}

Called Methods

No outgoing method calls

TransferCargoAtStationMove

Class: jfreerails.move.TransferCargoAtStationMove

Documentation

No documentation available

Source Code

public TransferCargoAtStationMove(ArrayList<Move> movesArrayList,
boolean waiting) {
super(movesArrayList);
this.waitingForFullLoad = waiting;
}

generateRelativeFileName

Class: jfreerails.client.renderer.AbstractTileRenderer

Documentation

No documentation available

Source Code

String generateRelativeFileName(int i) {
return "terrain" + File.separator + this.getTerrainType() + "_"
+ generateFileNameNumber(i) + ".png";
}

assertCorrectTotalAddedOverYear

Class: jfreerails.server.CargoAtStationsGeneratorTest

Documentation

/**
* If, say, 14 units get added each year, some month we should add 1 and
* others we should add 2 such that over the year exactly 14 units get
* added.
*/

Source Code

/**
* If, say, 14 units get added each year, some month we should add 1 and
* others we should add 2 such that over the year exactly 14 units get
* added.
*/
private void assertCorrectTotalAddedOverYear(final int unitPerYear) {
CargoAtStationsGenerator cargoGenerator = new CargoAtStationsGenerator();
int amountAddedThisSoFar = 0;
for (int i = 0; i < 12; i++) {
amountAddedThisSoFar += cargoGenerator.calculateAmountToAdd(
unitPerYear, i);
}
assertEquals(unitPerYear, amountAddedThisSoFar);
}

toCurve

Class: experimental.TrackRenderer

Documentation

No documentation available

Source Code

CubicCurve2D.Double toCurve(Step a, Step b) {
float halfTile = tileWidth / 2;
Point2D.Double start, end, one, two;
start = new Point2D.Double();
start.x = tileWidth + (halfTile * a.deltaX);
start.y = tileWidth + (halfTile * a.deltaY);
one = controlPoint(start);
end = new Point2D.Double();
end.x = tileWidth + (halfTile * b.deltaX);
end.y = tileWidth + (halfTile * b.deltaY);
two = controlPoint(end);
CubicCurve2D.Double returnValue = new CubicCurve2D.Double();
returnValue.setCurve(start, one, two, end);
return returnValue;
}

getArray

Class: jfreerails.util.ArrayBase

Documentation

/**
* Get the array for another instance of this class. This is a convenience
* method to allow subclasses access to the backing array of other
* subclasses.
*
* @param other
* subclass instance to get array from
* @return backing array object
*/

Source Code

/**
* Get the array for another instance of this class. This is a convenience
* method to allow subclasses access to the backing array of other
* subclasses.
*
* @param other
* subclass instance to get array from
* @return backing array object
*/
protected static Object getArray(ArrayBase other) {
return other.getArray();
}

paintComponent

Class: jfreerails.client.view.DateJLabel

Documentation

No documentation available

Source Code

@Override
protected void paintComponent(Graphics g) {
if (null != w) {
GameTime time = w.currentTime();
GameCalendar gameCalendar = (GameCalendar) w.get(ITEM.CALENDAR);
String s = gameCalendar.getYearAndMonth(time.getTicks());
super.setText(s);
}
super.paintComponent(g);
}

testCalculate

Class: jfreerails.controller.StockPriceCalculatorTest

Documentation

No documentation available

Source Code

public void testCalculate() {
Money stockPrice = calc.calculate()[0].currentPrice;
assertEquals(new Money(10), stockPrice);
advanceTimeOneTick();
addIncome(100000);
calc.calculate();
stockPrice = calc.calculate()[0].currentPrice;
assertEquals(new Money(10), stockPrice);
advanceTimeOneYear();
calc.calculate();
stockPrice = calc.calculate()[0].currentPrice;
assertEquals(new Money(11), stockPrice);
}

startThread

Class: jfreerails.launcher.Launcher

Documentation

/** Starts the client and server in the same thread. */

Source Code

/** Starts the client and server in the same thread. */
private static void startThread(final FreerailsGameServer server,
final GUIClient client) {
try {
Runnable run = new Runnable() {
public void run() {
while (null == client.getWorld()) {
client.update();
server.update();
}
GameModel[] models = new GameModel[] { client, server };
ScreenHandler screenHandler = client.getScreenHandler();
GameLoop gameLoop = new GameLoop(screenHandler, models);
//screenHandler.apply();
gameLoop.run();
}
};
Thread t = new Thread(run, "Client + server main loop");
t.start();
} catch (Exception e) {
exit(e);
}
}

mouseMoved

Class: jfreerails.client.view.StationPlacementCursor

Documentation

No documentation available

Source Code

@Override
public void mouseMoved(MouseEvent e) {
if (stationBuildModel.isPositionFollowsMouse()) {
Point p = e.getPoint();
Point mapCoord = new Point((int) (p.x / scale), (int) (p.y / scale));
stationBuildModel.getStationBuildAction().putValue(
StationBuildModel.StationBuildAction.STATION_POSITION_KEY,
mapCoord);
}
}

assertException

Class: jfreerails.world.common.PositionOnTrackTest

Documentation

No documentation available

Source Code

private void assertException(int x, int y, Step v) {
try {
PositionOnTrack.createComingFrom(x, y, v);
assertTrue(false);
} catch (Exception e) {
}
}

TrainMaintenanceMoveGenerator

Class: jfreerails.server.TrainMaintenanceMoveGenerator

Documentation

No documentation available

Source Code

public TrainMaintenanceMoveGenerator(MoveReceiver mr) {
this.moveReceiver = mr;
}

Called Methods

No outgoing method calls

is

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public boolean is(ModelRoot.Property p, Object value) {
return getProperty(p).equals(value);
}

setButtonsVisible

Class: jfreerails.launcher.Launcher

Documentation

No documentation available

Source Code

public void setButtonsVisible(boolean b){
nextButton.setVisible(b);
prevButton.setVisible(b);
}

Called Methods

No outgoing method calls

showContent

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showContent(JComponent component) {
closeContent();
JComponent contentPanel;
if (component instanceof JInternalFrame) {
dialogueJInternalFrame = (JInternalFrame) component;
} else {
if (!(component instanceof View)) {
contentPanel = new javax.swing.JPanel();
contentPanel.setLayout(new java.awt.GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.insets = new Insets(7, 7, 7, 7);
contentPanel.add(component, constraints);
constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 1;
constraints.insets = new Insets(7, 7, 7, 7);
contentPanel.add(closeButton, constraints);
} else {
contentPanel = component;
}
dialogueJInternalFrame = new JInternalFrame();
dialogueJInternalFrame.setFrameIcon(null);
dialogueJInternalFrame.getContentPane().add(contentPanel);
dialogueJInternalFrame.pack();
}
/*
* Make sure the size of the dialogue does not exceed the size of the
* frames content pane.
*/
int parentWidth = frame.getContentPane().getWidth();
int parentHeight = frame.getContentPane().getHeight();
Dimension size = dialogueJInternalFrame.getSize();
if (size.width > parentWidth) {
size.width = parentWidth;
}
if (size.height > parentHeight) {
size.height = parentHeight;
}
dialogueJInternalFrame.setSize(size);
dialogueJInternalFrame.setLocation(
(frame.getWidth() - dialogueJInternalFrame.getWidth()) / 2,
(frame.getHeight() - dialogueJInternalFrame.getHeight()) / 2);
frame.getLayeredPane().add(dialogueJInternalFrame,
JLayeredPane.MODAL_LAYER);
dialogueJInternalFrame.setVisible(true);
}

hashCode

Class: jfreerails.world.common.GameSpeed

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return speed;
}

Called Methods

No outgoing method calls

BrokerScreenGenerator

Class: jfreerails.client.view.BrokerScreenGenerator

Documentation

/** Creates a new instance of BrokerScreenGenerator */

Source Code

/** Creates a new instance of BrokerScreenGenerator */
public BrokerScreenGenerator(ReadOnlyWorld w, FreerailsPrincipal principal) {
dataGatherer = new FinancialDataGatherer(w, principal);
int playerId = w.getID(principal);
this.playername = w.getPlayer(playerId).getName();
this.cal = (GameCalendar) w.get(ITEM.CALENDAR);
GameTime time = w.currentTime();
final int startyear = cal.getYear(time.getTicks());
this.year = String.valueOf(startyear);
this.cash = w.getCurrentBalance(principal);
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
w, principal);
aggregator.setCategory(BOND);
this.loansTotal = aggregator.calculateValue();
this.publicShares = DC.format(dataGatherer.sharesHeldByPublic());
this.netWorth = dataGatherer.netWorth();
StockPrice[] stockPrices = (new StockPriceCalculator(w)).calculate();
this.pricePerShare = stockPrices[playerId].currentPrice;
this.treasuryStock = DC.format(dataGatherer.treasuryStock());
StringBuffer otherRRsStakes = new StringBuffer();
int[] stockInThisRRs = dataGatherer.getStockInThisRRs();
for (int i = 0; i < stockInThisRRs.length; i++) {
if (i != playerId && stockInThisRRs[i] > 0) {
String otherRRName = w.getPlayer(i).getName();
String otherRRStake = DC.format(stockInThisRRs[i]);
otherRRsStakes.append("<tr> ");
otherRRsStakes.append("<td> </td>");
otherRRsStakes.append("<td> </td>");
otherRRsStakes.append("<td>" + otherRRName + "</td>");
otherRRsStakes.append("<td>" + otherRRStake + "</td>");
otherRRsStakes.append("</tr>");
}
}
othersRRsStockRows = otherRRsStakes.toString();
}

autoConsistJMenuItemActionPerformed

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void autoConsistJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_autoConsistJMenuItemActionPerformed
setAutoConsist();
}// GEN-LAST:event_autoConsistJMenuItemActionPerformed

getRemoveTrackChangeTrackPieceMove

Class: jfreerails.move.ChangeTrackPieceCompositeMove

Documentation

No documentation available

Source Code

// utility method.
private static TrackMove getRemoveTrackChangeTrackPieceMove(ImPoint p,
Step direction, ReadOnlyWorld w, FreerailsPrincipal principal)
throws Exception {
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
if (w.boundsContain(p.x, p.y)) {
oldTrackPiece = ((FreerailsTile) w.getTile(p.x, p.y)).getTrackPiece();
if (oldTrackPiece.getTrackRule() != NullTrackType.getInstance()) {
TrackConfiguration trackConfiguration = TrackConfiguration
.subtract(oldTrackPiece.getTrackConfiguration(),
direction);
if (trackConfiguration != TrackConfiguration
.getFlatInstance("000010000")) {
int owner = getOwner(principal, w);
newTrackPiece = new TrackPieceImpl(trackConfiguration,
oldTrackPiece.getTrackRule(), owner, oldTrackPiece
.getTrackTypeID());
} else {
newTrackPiece = NullTrackPiece.getInstance();
}
} else {
// There is no track to remove.
// Fix for bug [ 948670 ] Removing non-existent track
throw new Exception();
}
} else {
newTrackPiece = NullTrackPiece.getInstance();
oldTrackPiece = NullTrackPiece.getInstance();
}
ChangeTrackPieceMove m = new ChangeTrackPieceMove(oldTrackPiece,
newTrackPiece, p);
// If we are removing a station, we also need to remove the station from
// the station list.
if (oldTrackPiece.getTrackRule().isStation()
&& !newTrackPiece.getTrackRule().isStation()) {
return RemoveStationMove.getInstance(w, m, principal);
}
return m;
}

setupWorld

Class: jfreerails.move.ChangeTileMoveTest

Documentation

No documentation available

Source Code

@Override
protected void setupWorld() {
world = MapFixtureFactory2.getCopy();
}

List3DDiff

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

public List3DDiff(SortedMap<ListKey, Object> diffs, List3D<T> list,
Enum listID) {
super(diffs, listID);
this.underlyingList = list;
}

generateInitialSchedule

Class: jfreerails.server.TrainUpdater

Documentation

No documentation available

Source Code

private ImmutableSchedule generateInitialSchedule(
FreerailsPrincipal principal, ReadOnlyWorld world,
boolean autoSchedule) {
WorldIterator wi = new NonNullElements(KEY.STATIONS, world, principal);
MutableSchedule s = new MutableSchedule();
// Add upto 4 stations to the schedule.
while (wi.next() && s.getNumOrders() < 5) {
TrainOrdersModel orders = new TrainOrdersModel(wi.getIndex(), null,
false, autoSchedule);
s.addOrder(orders);
}
s.setOrderToGoto(0);
ImmutableSchedule is = s.toImmutableSchedule();
return is;
}

equals

Class: jfreerails.world.train.TrainOrdersModel

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof TrainOrdersModel))
return false;
final TrainOrdersModel trainOrdersModel = (TrainOrdersModel) o;
if (autoConsist != trainOrdersModel.autoConsist)
return false;
if (stationId != trainOrdersModel.stationId)
return false;
if (waitUntilFull != trainOrdersModel.waitUntilFull)
return false;
if (consist != null ? !consist.equals(trainOrdersModel.consist)
: trainOrdersModel.consist != null)
return false;
return true;
}

Conversion

Class: jfreerails.world.terrain.Conversion

Documentation

No documentation available

Source Code

public Conversion(int in, int out) {
input = in;
output = out;
}

Called Methods

No outgoing method calls

saveProps

Class: jfreerails.launcher.Launcher

Documentation

No documentation available

Source Code

public void saveProps(){
try{
FileOutputStream out = new FileOutputStream("freerails.properties");
props.store(out, "---No Comment---");
out.close();
//Copy key-value pairs to System.Properties so
//that they are visible in the game via the
//show java properties menu item.
System.getProperties().putAll(props);
}catch (Exception e){
logger.warning(e.getMessage());
}
}

Called Methods

No outgoing method calls

IntArray

Class: jfreerails.util.IntArray

Documentation

/**
* Constructor with full specification.
*
* @param size
* number of <code>int</code> values initially allowed in array
* @param growth
* maximum size increment for growing array
*/

Source Code

/**
* Constructor with full specification.
*
* @param size
* number of <code>int</code> values initially allowed in array
* @param growth
* maximum size increment for growing array
*/
public IntArray(int size, int growth) {
super(size, growth, int.class);
}

ImPoint

Class: jfreerails.world.common.ImPoint

Documentation

No documentation available

Source Code

public ImPoint(Point p) {
x = p.x;
y = p.y;
}

Called Methods

No outgoing method calls

countOpenConnections

Class: jfreerails.network.GameServer

Documentation

No documentation available

Source Code

int countOpenConnections();

Called Methods

No outgoing method calls

removeLastD2

Class: jfreerails.util.List3D

Documentation

No documentation available

Source Code

void removeLastD2(int d1);

Called Methods

No outgoing method calls

testSubPath

Class: jfreerails.world.train.PathOnTilesTest

Documentation

No documentation available

Source Code

public void testSubPath() {
ImPoint start = new ImPoint();
Step[] vectors = new Step[] { EAST, EAST, EAST };
PathOnTiles path = new PathOnTiles(start, vectors);
// First check.
FreerailsPathIterator pathIt = path.subPath(0, path.getTotalDistance());
ImPoint[] expected = { new ImPoint(15, 15), new ImPoint(45, 15),
new ImPoint(75, 15), new ImPoint(105, 15) };
checkPath(pathIt, expected);
// Second check
pathIt = path.subPath(3, path.getTotalDistance() - 3);
expected = new ImPoint[] { new ImPoint(18, 15), new ImPoint(45, 15),
new ImPoint(75, 15), new ImPoint(105, 15) };
checkPath(pathIt, expected);
// 3rd check
double i = path.getTotalDistance() - 10;
pathIt = path.subPath(3, i);
expected = new ImPoint[] { new ImPoint(18, 15), new ImPoint(45, 15),
new ImPoint(75, 15), new ImPoint(98, 15) };
checkPath(pathIt, expected);
// 4th check, with a path just 1 tile long.
start = new ImPoint(5, 5);
vectors = new Step[] { SOUTH_WEST };
path = new PathOnTiles(start, vectors);
pathIt = path.subPath(18, 24);
IntLine line = new IntLine();
assertTrue(pathIt.hasNext());
pathIt.nextSegment(line);
assertEquals("The length of the train.", 24, line.getLength(), 1d);
assertFalse(pathIt.hasNext());
// 5th check, same as 2nd but with different starting position.
vectors = new Step[] { EAST, EAST, EAST };
start = new ImPoint(4, 7);
path = new PathOnTiles(start, vectors);
pathIt = path.subPath(3, path.getTotalDistance() - 3);
expected = new ImPoint[] { new ImPoint(18, 15), new ImPoint(45, 15),
new ImPoint(75, 15), new ImPoint(105, 15) };
for (int j = 0; j < expected.length; j++) {
int x = expected[j].x + start.x * TILE_DIAMETER;
int y = expected[j].y + start.y * TILE_DIAMETER;
expected[j] = new ImPoint(x, y);
}
// for (ImPoint point : expected) {
// point.x += start.x * TILE_DIAMETER;
// point.y += start.y * TILE_DIAMETER;
// }
checkPath(pathIt, expected);
}

MessageStatus

Class: jfreerails.controller.MessageStatus

Documentation

No documentation available

Source Code

public MessageStatus(int id, boolean successful, String reason) {
this.id = id;
this.reason = reason;
this.successful = successful;
}

Called Methods

No outgoing method calls

initComponents

Class: jfreerails.launcher.ProgressJPanel

Documentation

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/

Source Code

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
progressBar = new javax.swing.JProgressBar();
splashImage = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.insets = new java.awt.Insets(3, 7, 3, 7);
add(progressBar, gridBagConstraints);
splashImage.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
splashImage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/jfreerails/client/graphics/splash_screen.jpg")));
add(splashImage, new java.awt.GridBagConstraints());
}

Called Methods

No outgoing method calls

assertTrackHere

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

protected void assertTrackHere(int x, int y) {
FreerailsTile tile = (FreerailsTile) world.getTile(x, y);
assertTrue(tile.hasTrack());
}

getConsumption

Class: jfreerails.world.terrain.TileTypeImpl

Documentation

No documentation available

Source Code

public ImList<Consumption> getConsumption() {
return consumption;
}

Called Methods

No outgoing method calls

addConnection

Class: jfreerails.network.GameServer

Documentation

No documentation available

Source Code

void addConnection(Connection2Client connection);

Called Methods

No outgoing method calls

set

Class: jfreerails.world.top.World

Documentation

/**
* Replaces the element mapped to the specified item with the specified
* element.
*
*/

Source Code

/**
* Replaces the element mapped to the specified item with the specified
* element.
*
*/
void set(ITEM item, FreerailsSerializable element);

Called Methods

No outgoing method calls

currentRate

Class: jfreerails.util.FlowRateInputStream

Documentation

No documentation available

Source Code

public int currentRate() {
return (int) (byteReceivedCumul / 1024D / (nbUsed * (measureInterval / 1000D)));
}

Called Methods

No outgoing method calls

getOpposite

Class: jfreerails.world.common.Step

Documentation

/**
* Returns a new oneTileMoveVector whose direction is opposite to that the
* current one.
*
* @return A oneTileMoveVector.
*/

Source Code

/**
* Returns a new oneTileMoveVector whose direction is opposite to that the
* current one.
*
* @return A oneTileMoveVector.
*/
public Step getOpposite() {
return getInstance(this.deltaX * -1, this.deltaY * -1);
}

addCargoAtStation

Class: jfreerails.controller.MoveTrainPreMove2ndTest

Documentation

/** Adds the specified amount of cargo #0 to the specified station. */

Source Code

/** Adds the specified amount of cargo #0 to the specified station. */
private void addCargoAtStation(int stationId, int amount) {
CargoBatch cb = new CargoBatch(0, 6, 6, 0, stationId);
MutableCargoBundle mb = new MutableCargoBundle();
mb.addCargo(cb, amount);
StationModel station1Model = (StationModel) world.get(principal, KEY.STATIONS, stationId);
ImmutableCargoBundle cargoAtStationBefore = mb.toImmutableCargoBundle();
int station1BundleId = station1Model.getCargoBundleID();
world.set(principal, KEY.CARGO_BUNDLES, station1BundleId, cargoAtStationBefore);
}

toString

Class: jfreerails.controller.MyDisplayMode

Documentation

No documentation available

Source Code

@Override
public String toString() {
return displayMode.getWidth() + "x" + displayMode.getHeight() + " "
+ displayMode.getBitDepth() + " bit "
+ displayMode.getRefreshRate() + "Hz";
}

Called Methods

No outgoing method calls

getMonth

Class: jfreerails.world.common.GameCalendar

Documentation

/** Returns the month, 0=Jan, 1=Feb, etc. */

Source Code

/** Returns the month, 0=Jan, 1=Feb, etc. */
public int getMonth(int i) {
int ticksPerMonth = ticksPerYear / 12;
return (i % ticksPerYear) / ticksPerMonth;
}

Called Methods

No outgoing method calls

scrollbackgroundBuffer

Class: jfreerails.client.renderer.BufferedTiledBackgroundRenderer

Documentation

No documentation available

Source Code

private void scrollbackgroundBuffer(int dx, int dy) {
int copyWidth = bufferRect.width;
int copyHeight = bufferRect.height;
int copySourceX = 0;
int copySourceY = 0;
if (dx > 0) {
copyWidth -= dx;
} else {
copyWidth += dx;
copySourceX = -dx;
}
if (dy > 0) {
copyHeight -= dy;
} else {
copyHeight += dy;
copySourceY = -dy;
}
bg.copyArea(copySourceX, copySourceY, copyWidth, copyHeight, dx, dy);
bufferRect.x -= dx;
bufferRect.y -= dy;
// paint exposed areas
if (dx != 0) {
if (dx > 0) {
bg.setClip(0, 0, dx, bufferRect.height);
bg.clearRect(0, 0, dx, bufferRect.height);
paintBufferRectangle(0, 0, dx, bufferRect.height);
} else {
bg.setClip(bufferRect.width + dx, 0, -dx, bufferRect.height);
bg.clearRect(bufferRect.width + dx, 0, -dx, bufferRect.height);
paintBufferRectangle(bufferRect.width + dx, 0, -dx,
bufferRect.height);
}
}
if (dy != 0) {
if (dy > 0) {
bg.setClip(0, 0, bufferRect.width, dy);
bg.clearRect(0, 0, bufferRect.width, dy);
paintBufferRectangle(0, 0, bufferRect.width, dy);
} else {
bg.setClip(0, bufferRect.height + dy, bufferRect.width, -dy);
bg.clearRect(0, bufferRect.height + dy, bufferRect.width, -dy);
paintBufferRectangle(0, bufferRect.height + dy,
bufferRect.width, -dy);
}
}
bg.setClip(0, 0, bufferRect.width, bufferRect.height);
}

refreshAll

Class: jfreerails.client.renderer.MapLayerRenderer

Documentation

No documentation available

Source Code

void refreshAll();

Called Methods

No outgoing method calls

removeLast

Class: jfreerails.util.List1DDiff

Documentation

No documentation available

Source Code

public T removeLast() {
return super.removeLast();
}

refreshAll

Class: jfreerails.client.renderer.TerrainLayer

Documentation

No documentation available

Source Code

public void refreshAll() {
}

Called Methods

No outgoing method calls

tryDoMove

Class: jfreerails.move.ChangeGameSpeedMove

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.get(ITEM.GAME_SPEED).equals(oldSpeed)) {
return MoveStatus.MOVE_OK;
}
String string = "oldSpeed = " + oldSpeed.getSpeed() + " <=> "
+ "currentSpeed "
+ ((GameSpeed) w.get(ITEM.GAME_SPEED)).getSpeed();
return MoveStatus.moveFailed(string);
}

toInt

Class: jfreerails.world.common.PositionOnTrack

Documentation

/**
* @return an integer representing this PositionOnTrack object
*/

Source Code

/**
* @return an integer representing this PositionOnTrack object
*/
public int toInt() {
int i = x | (y << BITS_FOR_COORDINATE);
int directionAsInt = cameFrom.getID();
int shiftedDirection = (directionAsInt << (2 * BITS_FOR_COORDINATE));
i = i | shiftedDirection;
return i;
}

get

Class: jfreerails.util.ListXDDiffs

Documentation

No documentation available

Source Code

@SuppressWarnings("unchecked")
public T get(int... i) {
checkBounds(i);
ListKey elementKey = new ListKey(ListKey.Type.Element, listID, i);
if (diffs.containsKey(elementKey)) {
return (T) diffs.get(elementKey);
}
return uGet(i);
}

hashCode

Class: jfreerails.world.top.TestState

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return x;
}

Called Methods

No outgoing method calls

getState

Class: jfreerails.world.common.ActivityIterator

Documentation

No documentation available

Source Code

FreerailsSerializable getState(double absoluteTime);

Called Methods

No outgoing method calls

waitForObjectFromServer

Class: jfreerails.network.InetConnection2Server

Documentation

No documentation available

Source Code

public FreerailsSerializable waitForObjectFromServer() throws IOException,
InterruptedException {
return waitForObject();
}

findNearestStationInDirection

Class: jfreerails.client.view.NearestStationFinder

Documentation

No documentation available

Source Code

public int findNearestStationInDirection(int startStation, Step direction) {
int distanceToClosestSquared = Integer.MAX_VALUE;
NonNullElements it = new NonNullElements(KEY.STATIONS, world, principal);
StationModel currentStation = (StationModel) world.get(principal,
KEY.STATIONS, startStation);
int nearestStation = NOT_FOUND;
while (it.next()) {
StationModel station = (StationModel) it.getElement();
int deltaX = station.x - currentStation.x;
int deltaY = station.y - currentStation.y;
int distanceSquared = deltaX * deltaX + deltaY * deltaY;
boolean closer = distanceSquared < distanceToClosestSquared;
boolean notTheSameStation = startStation != it.getIndex();
boolean inRightDirection = isInRightDirection(direction, deltaX,
deltaY);
if (closer && inRightDirection && notTheSameStation) {
distanceToClosestSquared = distanceSquared;
nearestStation = it.getIndex();
}
}
return nearestStation;
}

paintRectangleOfTiles

Class: jfreerails.client.renderer.TrackLayer

Documentation

/**
* Paints a rectangle of tiles onto the supplied graphics context.
*
* @param g
* The graphics context on which the tiles get painted.
* @param tilesToPaint
* The rectangle, measured in tiles, to paint.
*/

Source Code

/**
* Paints a rectangle of tiles onto the supplied graphics context.
*
* @param g
* The graphics context on which the tiles get painted.
* @param tilesToPaint
* The rectangle, measured in tiles, to paint.
*/
public void paintRectangleOfTiles(Graphics g, Rectangle tilesToPaint) {
/*
* Track can overlap the adjacent terrain tiles by half a tile. This
* means that we need to paint the track from the tiles bordering
* the specified rectangle of tiles (tilesToPaint). To prevent
* unnecessary painting, we set the clip to expose only the rectangle
* of tilesToPaint.
*/
Graphics tempG = g;
Point tile = new Point();
for (tile.x = tilesToPaint.x - 1; tile.x < (tilesToPaint.x
+ tilesToPaint.width + 1); tile.x++) {
for (tile.y = tilesToPaint.y - 1; tile.y < (tilesToPaint.y
+ tilesToPaint.height + 1); tile.y++) {
if ((tile.x >= 0) && (tile.x < mapSize.width)
&& (tile.y >= 0) && (tile.y < mapSize.height)) {
FreerailsTile ft = (FreerailsTile)w.getTile(tile.x, tile.y);
TrackPiece tp = ft.getTrackPiece();
int graphicsNumber = tp.getTrackGraphicID();
int ruleNumber = tp.getTrackTypeID();
if (ruleNumber != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER) {
TrackPieceRenderer trackPieceView = rr.getTrackPieceView(ruleNumber);
trackPieceView.drawTrackPieceIcon(graphicsNumber,
tempG, tile.x, tile.y, tileSize);
}
}
}
}
}

updateUntilComplete

Class: jfreerails.client.renderer.BuildTrackController

Documentation

No documentation available

Source Code

public void updateUntilComplete() {
while (searchStatus() != IncrementalPathFinder.PATH_FOUND) {
updateSearch();
}
}

setUp

Class: jfreerails.network.specifics.FreerailsGameServerTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
server = new FreerailsGameServer(new SavedGamesManager4UnitTests());
}

Called Methods

No outgoing method calls

TrainOrdersListElement

Class: jfreerails.client.view.TrainOrdersListElement

Documentation

No documentation available

Source Code

public TrainOrdersListElement(boolean isPriorityOrder, int gotoStatus,
TrainOrdersModel order, int trainNumber) {
this.isPriorityOrder = isPriorityOrder;
this.gotoStatus = gotoStatus;
this.order = order;
this.trainNumber = trainNumber;
}

Called Methods

No outgoing method calls

calProfit

Class: jfreerails.controller.Stats

Documentation

No documentation available

Source Code

private void calProfit(){
long profitValue = operatingFunds.getAmount() + track.getAmount()
+ stations.getAmount() + rollingStock.getAmount()
+ industries.getAmount() + loans.getAmount()
+ equity.getAmount() + treasuryStock.getAmount()
+ otherRrStock.getAmount();
profit= new Money(profitValue);
}

logSpeed

Class: jfreerails.client.top.UserMessageGenerator

Documentation

No documentation available

Source Code

public void logSpeed() {
ReadOnlyWorld world = modelRoot.getWorld();
GameSpeed speed = ((GameSpeed) world.get(ITEM.GAME_SPEED));
int gameSpeed = speed.getSpeed();
if (gameSpeed <= 0) {
modelRoot
.setProperty(Property.PERMANENT_MESSAGE, "Game is paused.");
/*
* Also hide any other message. It looks silly if it says "Game is
* paused." and "Game speed: fast" on screen at the same time!
*/
modelRoot.setProperty(Property.QUICK_MESSAGE, "");
} else {
modelRoot.setProperty(Property.PERMANENT_MESSAGE, null);
String gameSpeedDesc = actionRoot.getServerControls()
.getGameSpeedDesc(gameSpeed);
modelRoot.setProperty(Property.QUICK_MESSAGE, "Game speed: "
+ gameSpeedDesc);
}
}

addTransaction

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public void addTransaction(FreerailsPrincipal p, Transaction t) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = new TransactionAndTimeStamp(t, time);
bankAccounts.addD2(playerIndex, tats);
Money oldBalance = currentBalance.get(playerIndex);
Money newBalance = new Money(t.deltaCash().getAmount()
+ oldBalance.getAmount());
currentBalance.set(playerIndex, newBalance);
}

testAddTrackMove

Class: jfreerails.move.TrackMoveTransactionsGeneratorTest

Documentation

No documentation available

Source Code

public void testAddTrackMove() {
TrackPiece oldTrackPiece;
TrackPiece newTrackPiece;
TrackConfiguration newConfig;
TrackMove move;
// Try building the simplest piece of track.
newConfig = TrackConfiguration.getFlatInstance("000010000");
oldTrackPiece = ((FreerailsTile) world.getTile(0, 0)).getTrackPiece();
TrackRule r = (TrackRule) world.get(SKEY.TRACK_RULES, 0);
int owner = ChangeTrackPieceCompositeMove.getOwner(
MapFixtureFactory.TEST_PRINCIPAL, world);
newTrackPiece = new TrackPieceImpl(newConfig, r, owner, 0);
move = new ChangeTrackPieceMove(oldTrackPiece, newTrackPiece,
new ImPoint(0, 0));
Move m = transactionGenerator.addTransactions(move);
assertNotNull(m);
}

testBuyingStock

Class: jfreerails.client.view.BrokerScreenGeneratorTest

Documentation

/**
* Testcase to reproduce bug [ 1341365 ] Exception when calculating stock
* price after buying shares
*/

Source Code

/**
* Testcase to reproduce bug [ 1341365 ] Exception when calculating stock
* price after buying shares
*/
public void testBuyingStock() {
for (int i = 0; i < 9; i++) {
StockPrice stockPrice = new StockPriceCalculator(world).calculate()[playerID];
Money sharePrice = stockPrice.treasuryBuyPrice;
StockTransaction t = StockTransaction.buyOrSellStock(playerID,
StockTransaction.STOCK_BUNDLE_SIZE, sharePrice);
Move move = new AddTransactionMove(principal, t);
MoveStatus ms = move.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.isOk());
//The line below threw an exception that caused bug 1341365.
BrokerScreenGenerator brokerScreenGenerator = new BrokerScreenGenerator(world, principal);
assertNotNull(brokerScreenGenerator);
}
}

setBorderColor

Class: jfreerails.client.renderer.StationRadiusRenderer

Documentation

No documentation available

Source Code

public void setBorderColor(Color c) {
borderColor = c;
}

Called Methods

No outgoing method calls

getSelectedTrainID

Class: jfreerails.client.view.TrainListJPanel

Documentation

No documentation available

Source Code

int getSelectedTrainID() {
/*
* Note, the selected index is not the train id since trains that have
* been removed are not shown on the list.
*/
int row = jList1.getSelectedIndex();
if (row == -1) {
return -1;
} else {
return NonNullElements.row2index(world, KEY.TRAINS, principal, row);
}
}

initComponents

Class: jfreerails.client.view.NewsPaperJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() { // GEN-BEGIN:initComponents
headline = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
anyKeyToContinueJLabel = new javax.swing.JLabel();
setLayout(null);
setPreferredSize(new java.awt.Dimension(640, 400));
setMinimumSize(new java.awt.Dimension(640, 400));
setMaximumSize(new java.awt.Dimension(640, 400));
setOpaque(false);
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
headline.setPreferredSize(new java.awt.Dimension(620, 110));
headline.setMinimumSize(new java.awt.Dimension(620, 110));
headline.setText("NEWSPAPER HEADLINE");
headline.setForeground(java.awt.Color.black);
headline.setBackground(java.awt.Color.white);
headline.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
headline.setFont(new java.awt.Font("Lucida Bright", 1, 36));
headline.setMaximumSize(new java.awt.Dimension(620, 110));
add(headline);
headline.setBounds(10, 70, 620, 110);
jPanel1.setBorder(new javax.swing.border.BevelBorder(0));
anyKeyToContinueJLabel.setText("Click to continue");
anyKeyToContinueJLabel.setForeground(java.awt.Color.black);
anyKeyToContinueJLabel.setBackground(java.awt.Color.darkGray);
jPanel1.add(anyKeyToContinueJLabel);
add(jPanel1);
jPanel1.setBounds(230, 260, 190, 30);
}

getNewType

Class: jfreerails.server.TerrainRandomiser

Documentation

No documentation available

Source Code

public int getNewType(int type) {
int newType = type;
double value;
double divide = 1.0 / terrainTypes.size();
// allow any terrain type to be drawn over except those listed in
// non_terrainTypes
if (!non_terrainTypes.contains(new Integer(newType))) {
if (Math.random() < CLEAR_PERCENTAGE) {
// make the tile Clear
return 4;
}
value = Math.random();
/*
* at the moment, this logic produces a balanced and even
* distribution of the different country tiles (currently 3).
* somehow it would be better to have the actual proportions of
* Farms, Jungle and Desert etc vary. dunno how.
*/
for (int i = 0; i < terrainTypes.size(); i++) {
if ((value > (i * divide)) && (value <= ((i + 1) * divide))) {
return terrainTypes.elementAt(i).intValue();
}
}
}
return newType;
}

Called Methods

No outgoing method calls

assertLineEquals

Class: jfreerails.controller.ToAndFroPathIteratorTest

Documentation

No documentation available

Source Code

private void assertLineEquals(int x1, int y1, int x2, int y2, IntLine line) {
assertEquals(x1, line.x1);
assertEquals(x2, line.x2);
assertEquals(y1, line.y1);
assertEquals(y2, line.y2);
}

Called Methods

No outgoing method calls

MapViewJComponent

Class: jfreerails.client.view.MapViewJComponent

Documentation

No documentation available

Source Code

public MapViewJComponent() {
this.setAutoscrolls(true);
}

Called Methods

No outgoing method calls

rejected

Class: jfreerails.network.specifics.LogOnResponse

Documentation

No documentation available

Source Code

public static LogOnResponse rejected(String reason) {
return new LogOnResponse(false, -1, reason);
}

Called Methods

No outgoing method calls

TrainPositionOnMap

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

private TrainPositionOnMap(int[] xs, int[] ys, double speed,
double acceleration, SpeedTimeAndStatus.TrainActivity activity) {
if (xs.length != ys.length) {
throw new IllegalArgumentException();
}
xpoints = new ImInts(xs);
ypoints = new ImInts(ys);
this.acceleration = acceleration;
this.speed = speed;
this.activity = activity;
}

Called Methods

No outgoing method calls

size

Class: jfreerails.world.top.WorldIterator

Documentation

/** Returns the number of rows. */

Source Code

/** Returns the number of rows. */
int size();

Called Methods

No outgoing method calls

paintComponent

Class: jfreerails.client.view.NetWorthGraphJPanel

Documentation

No documentation available

Source Code

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(2f, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_BEVEL));
// Draw guide lines.
g2.setStroke(new BasicStroke(1f, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_BEVEL));
g.setColor(Color.GRAY);
for (int y = 295; y > 50; y -= 60) {
g2.drawLine(graphRect.x, y, 420, y);
}
g2.setStroke(new BasicStroke(2f, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_BEVEL));
// Draw key
for (int i = 0; i < companies.size(); i++) {
int yOffset = i * 20;
CompanyDetails company = companies.get(i);
g2.setColor(company.color);
g2.drawLine(50, 70 + yOffset, 60, 70 + yOffset);
g2.setColor(Color.BLACK);
g2.setFont(FONT);
g.drawString(company.name, 65, 72 + yOffset);
}
// Draw graphs lines
for (int i = 0; i < companies.size(); i++) {
CompanyDetails company = companies.get(i);
g2.setColor(company.color);
for (int year = 1; year < 100; year++) {
if (company.value[year] != Integer.MIN_VALUE
&& company.value[year - 1] != Integer.MIN_VALUE) {
long x1 = year * graphRect.width / 100 + graphRect.x;
long y1 = company.value[year] * graphRect.height / scaleMax;
y1 = Math.max(1, y1);
y1 = graphRect.y + graphRect.height - y1;
long x2 = (year - 1) * graphRect.width / 100 + graphRect.x;
long y2 = company.value[year - 1] * graphRect.height
/ scaleMax;
y2 = Math.max(1, y2);
y2 = graphRect.y + graphRect.height - y2;
g2.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
}
}
}
// Draw axis
g2.setColor(Color.BLACK);
g2.drawLine(graphRect.x, graphRect.y, graphRect.x, graphRect.y
+ graphRect.height);
g2.drawLine(graphRect.x, graphRect.y + graphRect.height, graphRect.x
+ graphRect.width, graphRect.y + graphRect.height);
}

Called Methods

No outgoing method calls

getListCellRendererComponent

Class: jfreerails.client.view.TrainSummaryJPanel

Documentation

No documentation available

Source Code

public java.awt.Component getListCellRendererComponent(
javax.swing.JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
int trainID = NonNullElements
.row2index(w, KEY.TRAINS, principal, index);
trainNumLabel.setText("#" + (trainID + 1));
headingLabel.setText(findStationName(trainID));
trainMaintenanceCostLabel.setText(findMaintenanceCost());
trainIncomeLabel.setText(findTrainIncome(trainID));
java.awt.GridBagConstraints gridBagConstraints;
trainListCellRenderer1.setOpaque(true);
trainListCellRenderer1.setCenterTrain(false);
trainListCellRenderer1.display(trainID);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
gridBagConstraints.insets = new java.awt.Insets(3, 0, 3, 0);
add(trainListCellRenderer1, gridBagConstraints);
if (isSelected) {
if (list.isFocusOwner()) {
setBackground(selectedColor);
trainListCellRenderer1.setBackground(selectedColor);
} else {
setBackground(selectedColorNotFocused);
trainListCellRenderer1.setBackground(selectedColorNotFocused);
}
} else {
setBackground(backgroundColor);
trainListCellRenderer1.setBackground(backgroundColor);
}
// Set selected
return this;
}

startInMiddleOfSegment

Class: jfreerails.world.train.PathWalkerImpl

Documentation

No documentation available

Source Code

private void startInMiddleOfSegment(IntLine line) {
line.x1 = getCoordinateOnSegment(distanceAlongCurrentSegment,
currentSegment.x1, currentSegment.x2);
line.y1 = getCoordinateOnSegment(distanceAlongCurrentSegment,
currentSegment.y1, currentSegment.y2);
}

update

Class: jfreerails.util.GameModel

Documentation

No documentation available

Source Code

void update();

Called Methods

No outgoing method calls

getTrainB

Class: jfreerails.move.TrainCrashException

Documentation

No documentation available

Source Code

public int getTrainB() {
return trainB;
}

Called Methods

No outgoing method calls

getA

Class: jfreerails.util.Pair

Documentation

No documentation available

Source Code

public A getA() {
return e1;
}

Called Methods

No outgoing method calls

getDy

Class: jfreerails.world.common.Step

Documentation

/** Returns the Y component of the vector. */

Source Code

/** Returns the Y component of the vector. */
public int getDy() {
return deltaY;
}

Called Methods

No outgoing method calls

tryUndoMove

Class: jfreerails.move.AddItemToSharedListMove

Documentation

No documentation available

Source Code

public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int expectListSize = index + 1;
if (w.size(listKey) != expectListSize) {
return MoveStatus.moveFailed("Expected size of "
+ listKey.toString() + " list is " + expectListSize
+ " but actual size is " + w.size(listKey));
}
return MoveStatus.MOVE_OK;
}

read

Class: jfreerails.util.FlowRateInputStream

Documentation

No documentation available

Source Code

@Override
public int read(byte[] b) throws IOException {
int r = super.in.read(b);
totalByteReceived += r;
return r;
}

Called Methods

No outgoing method calls

formKeyPressed

Class: jfreerails.client.view.SelectStationJPanel

Documentation

No documentation available

Source Code

private void formKeyPressed(java.awt.event.KeyEvent evt) {// GEN-FIRST:event_formKeyPressed
try {
Step v = KeyCode2OneTileMoveVector.getInstanceMappedToKey(evt
.getKeyCode());
// now find nearest station in direction of the vector.
NearestStationFinder stationFinder = new NearestStationFinder(
this.world, this.principal);
int station = stationFinder.findNearestStationInDirection(
this.selectedStationID, v);
if (selectedStationID != station
&& station != NearestStationFinder.NOT_FOUND) {
selectedStationID = station;
cargoWaitingAndDemandedJPanel1.display(selectedStationID);
this.validate();
this.repaint();
}
} catch (NoSuchElementException e) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
needsUpdating = true;
submitButtonCallBack.actionPerformed(null);
}
// The key pressed isn't mapped to a OneTileMoveVector so do
// nothing.
}
}// GEN-LAST:event_formKeyPressed

stringTemplate2Int

Class: jfreerails.world.track.TrackConfiguration

Documentation

No documentation available

Source Code

public static int stringTemplate2Int(String templateString) {
// Hack - so that result is as expected by earlier written code.
StringBuffer strb = new StringBuffer(templateString);
strb = strb.reverse();
templateString = strb.toString();
// End of hack
return Integer.parseInt(templateString, 2);
}

Called Methods

No outgoing method calls

nextEdge

Class: jfreerails.controller.FlatTrackExplorer

Documentation

No documentation available

Source Code

public void nextEdge() {
if (!hasNextEdge()) {
throw new NoSuchElementException();
}
Step v = this.getFirstVectorToTry();
Point p = new Point(currentPosition.getX(), currentPosition.getY());
FreerailsTile ft = (FreerailsTile)w.getTile(p.x, p.y);
TrackPiece tp = ft.getTrackPiece();
TrackConfiguration conf = tp.getTrackConfiguration();
Step[] vectors = Step.getList();
int i = v.getID();
int loopCounter = 0;
while (!conf.contains(vectors[i].get9bitTemplate())) {
i++;
i = i % 8;
loopCounter++;
if (8 < loopCounter) {
throw new IllegalStateException();
// This should never happen.. ..but it does happen when you
// removed the track from under a train.
}
}
Step branchDirection = Step.getInstance(i);
this.currentBranch.setCameFrom(branchDirection);
int x = this.currentPosition.getX() + branchDirection.deltaX;
int y = this.currentPosition.getY() + branchDirection.deltaY;
this.currentBranch.setX(x);
this.currentBranch.setY(y);
beforeFirst = false;
}

CopyableTextJPanel

Class: jfreerails.controller.CopyableTextJPanel

Documentation

/** Creates new form CopyableTextJPanel */

Source Code

/** Creates new form CopyableTextJPanel */
public CopyableTextJPanel() {
initComponents();
}

arrivesAtPoint

Class: jfreerails.controller.TrainStopsHandler

Documentation

No documentation available

Source Code

public ImPoint arrivesAtPoint(int x, int y) {
TrainAccessor ta = new TrainAccessor(worldDiffs, principal, trainId);
ImPoint targetPoint = ta.getTarget();
if (x == targetPoint.x && y == targetPoint.y) {
updateTarget();
targetPoint = ta.getTarget();
} else {
int stationNumber = getStationID(x, y);
if (NOT_AT_STATION != stationNumber) {
loadAndUnloadCargo(stationNumber, false, false);
}
}
return targetPoint;
}

testMove

Class: jfreerails.move.AddPlayerMoveTest

Documentation

No documentation available

Source Code

@Override
public void testMove() {
Player newPlayer = new Player("New Player");
assertTrue("Check reflexivity of Player.equals(.)", Utils
.equalsBySerialization(newPlayer, newPlayer));
AddPlayerMove move = AddPlayerMove.generateMove(getWorld(), newPlayer);
assertSurvivesSerialisation(move);
assertDoThenUndoLeavesWorldUnchanged(move);
}

testDontDropOffCargo

Class: jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest

Documentation

/**
* Tests that a train does not drop cargo off at its station of origin
* unless it has to.
*/

Source Code

/**
* Tests that a train does not drop cargo off at its station of origin
* unless it has to.
*/
public void testDontDropOffCargo() {
// Set station to
setCargoOnTrain(cargoType0FromStation0, 50);
setCargoOnTrain(cargoType0FromStation2, 50);
stopAtStation();
// The train shouldn't have dropped anything off.
MutableCargoBundle expectedOnTrain = new MutableCargoBundle();
expectedOnTrain.setAmount(cargoType0FromStation0, 50);
expectedOnTrain.setAmount(cargoType0FromStation2, 50);
assertEquals(expectedOnTrain.toImmutableCargoBundle(),
getCargoOnTrain());
assertEquals(ImmutableCargoBundle.EMPTY_BUNDLE, getCargoAtStation());
// Now remove the wagons from the train.
removeAllWagonsFromTrain();
stopAtStation();
/*
* The train now has no wagons, so must drop off the cargo whether the
* station demands it or not. Since the station does not demand it, the
* cargo should get added to the cargo waiting at the station.
*/
MutableCargoBundle expectedAtStation = new MutableCargoBundle();
expectedAtStation.setAmount(cargoType0FromStation0, 50);
expectedAtStation.setAmount(cargoType0FromStation2, 50);
assertEquals(expectedAtStation.toImmutableCargoBundle(),
getCargoAtStation());
assertEquals(ImmutableCargoBundle.EMPTY_BUNDLE, getCargoOnTrain());
}

equals

Class: jfreerails.util.List1DImpl

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object obj) {
if (!(obj instanceof List1D))
return false;
return Lists.equals(this, (List1D) obj);
}

TrackPieceImpl

Class: jfreerails.world.track.TrackPieceImpl

Documentation

No documentation available

Source Code

public TrackPieceImpl(TrackConfiguration c, TrackRule type, int owner,
int rule) {
configuration = c;
trackType = type;
ownerID = owner;
ruleNumber = rule;
}

Called Methods

No outgoing method calls

incrTime

Class: jfreerails.controller.MoveTrainPreMove2ndTest

Documentation

No documentation available

Source Code

static void incrTime(World w, FreerailsPrincipal p) {
ActivityIterator ai = w.getActivities(p, 0);
while (ai.hasNext())
ai.nextActivity();
double finishTime = ai.getFinishTime();
GameTime newTime = new GameTime((int) Math.floor(finishTime));
w.setTime(newTime);
}

readResolve

Class: jfreerails.world.terrain.NullTerrainType

Documentation

No documentation available

Source Code

private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}

Called Methods

No outgoing method calls

BuildTrackExplorer

Class: jfreerails.controller.BuildTrackExplorer

Documentation

No documentation available

Source Code

public BuildTrackExplorer(ReadOnlyWorld w, FreerailsPrincipal principal,
ImPoint start, ImPoint target) {
world = w;
this.principal = principal;
PositionOnTrack pos;
if (null == start) {
pos = new PositionOnTrack();
} else {
pos = PositionOnTrack
.createComingFrom(start.x, start.y, Step.NORTH);
}
currentPosition.setValuesFromInt(pos.toInt());
directionInt = 0;
this.target = target;
buildTrackStrategy = BuildTrackStrategy.getDefault(w);
}

SetPropertyMessage2Client

Class: jfreerails.network.specifics.SetPropertyMessage2Client

Documentation

No documentation available

Source Code

public SetPropertyMessage2Client(int id, ClientProperty key,
FreerailsSerializable value) {
if (null == key || null == value)
throw new NullPointerException();
this.id = id;
this.key = key;
this.value = value;
}

Called Methods

No outgoing method calls

calcT

Class: jfreerails.world.train.ConstAcc

Documentation

No documentation available

Source Code

private static double calcT(double u, double a, double s) {
// Note, Utils.solveQuadratic throws an exception if a == 0
return a == 0 ? s / u : Utils.solveQuadratic(a * 0.5d, u, -s);
}

toString

Class: jfreerails.world.track.TrackSection

Documentation

No documentation available

Source Code

@Override
public String toString() {
return tile.toString()+ " "+ step.toString();
}

AddStationPreMove

Class: jfreerails.controller.AddStationPreMove

Documentation

No documentation available

Source Code

private AddStationPreMove(ImPoint p, int trackRule,
FreerailsPrincipal principal) {
this.p = p;
this.ruleNumber = trackRule;
this.principal = principal;
}

Called Methods

No outgoing method calls

getLoadGameAction

Class: jfreerails.client.view.ServerControlModel

Documentation

/**
* @return an action to load a game.
*/

Source Code

/**
* @return an action to load a game.
*/
public Action getLoadGameAction() {
return loadGameAction;
}

Called Methods

No outgoing method calls

testTryUndoMove

Class: jfreerails.move.ChangeTrackPieceMoveTest

Documentation

No documentation available

Source Code

public void testTryUndoMove() {
setUp();
}

undoMove

Class: jfreerails.move.CompositeMove

Documentation

No documentation available

Source Code

public final MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = MoveStatus.MOVE_OK;
for (int i = moves.size() - 1; i >= 0; i--) {
ms = moves.get(i).undoMove(w, p);
if (!ms.ok) {
// Redo any moves we have already undone.
redoMoves(w, i + 1, p);
return ms;
}
}
return ms;
}

Track_TilesParser

Class: jfreerails.server.parser.Track_TilesParser

Documentation

No documentation available

Source Code

public Track_TilesParser(final Track_TilesHandler handler) {
this.handler = handler;
buffer = new StringBuffer(111);
context = new java.util.Stack<Object[]>();
}

Called Methods

No outgoing method calls

writeToClient

Class: jfreerails.network.Connection2Client

Documentation

/** Sends the specified object to the client. */

Source Code

/** Sends the specified object to the client. */
void writeToClient(FreerailsSerializable object) throws IOException;

Called Methods

No outgoing method calls

createClientJFrame

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

public JFrame createClientJFrame(String title) {
clientJFrame.setTitle(title);
return clientJFrame;
}

Called Methods

No outgoing method calls

GUIClient

Class: jfreerails.launcher.GUIClient

Documentation

No documentation available

Source Code

public GUIClient(String name, FreerailsProgressMonitor fm, int screenMode,
DisplayMode dm) throws IOException {
this.name = name;
this.monitor = null == fm ? this : fm;
// Set up model root and action root.
modelRoot = new ModelRootImpl();
modelRoot.setMoveFork(this.getMoveFork());
modelRoot.setMoveReceiver(this);
modelRoot.setServerCommandReceiver(this);
actionRoot = new ActionRoot(modelRoot);
// Create GUI components
factory = new GUIComponentFactoryImpl(modelRoot, actionRoot);
JFrame createClientJFrame = factory.createClientJFrame(name);
screenHandler = new ScreenHandler(createClientJFrame, screenMode, dm);
}

sizeD1

Class: jfreerails.util.List2D

Documentation

No documentation available

Source Code

int sizeD1();

Called Methods

No outgoing method calls

updateHtml

Class: jfreerails.client.view.IncomeStatementHtmlJPanel

Documentation

No documentation available

Source Code

private void updateHtml() {
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
IncomeStatementGenerator balanceSheetGenerator = new IncomeStatementGenerator(
world, playerPrincipal);
String populatedTemplate = populateTokens(template,
balanceSheetGenerator);
setHtml(populatedTemplate);
}

hashCode

Class: jfreerails.world.player.Player

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return name.hashCode();
}

Called Methods

No outgoing method calls

startElement

Class: jfreerails.server.CitySAXParser

Documentation

No documentation available

Source Code

@Override
public void startElement(String namespaceURI, String sName, String qName,
Attributes attrs) throws SAXException {
String cityName = null;
int x = 0;
int y = 0;
if (attrs != null) {
for (int i = 0; i < attrs.getLength(); i++) {
String aName = attrs.getLocalName(i); // Attr name
if (aName.equals("")) {
aName = attrs.getQName(i);
}
// put values in CityModel obj
if (aName.equals("name")) {
cityName = attrs.getValue(i);
}
if (aName.equals("x")) {
x = Integer.parseInt(attrs.getValue(i));
}
if (aName.equals("y")) {
y = Integer.parseInt(attrs.getValue(i));
CityModel city = new CityModel(cityName, x, y);
cities.addElement(city);
}
}
// end for loop
}
// end if
}

Called Methods

No outgoing method calls

getListCellRendererComponent

Class: jfreerails.client.view.TrainOrderJPanel

Documentation

No documentation available

Source Code

public java.awt.Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus) {
TrainOrdersListModel.TrainOrdersListElement trainOrders = (TrainOrdersListModel.TrainOrdersListElement) value;
// Set station name
int stationNumber = trainOrders.order.stationId;
StationModel station = (StationModel) w.get(principal,
KEY.STATIONS, stationNumber);
String stationName = station.getStationName();
this.stationNameJLabel.setText(stationName);
// Set wait until full
String waitUntilFull = trainOrders.order.waitUntilFull ? "Wait until full"
: "";
this.ordersJLabel.setText(waitUntilFull);
// Set selected
if (isSelected) {
if (list.isFocusOwner()) {
setBackground(selectedColor);
} else {
setBackground(selectedColorNotFocused);
}
} else {
setBackground(backgroundColor);
}
// Set goto status.
switch (trainOrders.gotoStatus) {
case TrainOrdersListModel.DONT_GOTO:
this.gotoIcon.setIcon(this.dontGoto);
break;
case TrainOrdersListModel.GOTO_AFTER_PRIORITY_ORDERS:
this.gotoIcon.setIcon(this.gotoAfterPriorityOrders);
break;
case TrainOrdersListModel.GOTO_NOW:
this.gotoIcon.setIcon(this.gotoNow);
break;
default:
throw new IllegalArgumentException(String
.valueOf(trainOrders.gotoStatus));
}
this.gotoIcon.setPreferredSize(new Dimension(20, 20));
// Set consist
TrainListCellRenderer trainViewJPanel = (TrainListCellRenderer) consistChangeJPanel;
trainViewJPanel.display(trainOrders.trainNumber, index);
// Show priority orders.
if (trainOrders.isPriorityOrder) {
// Write the station name in upper case
String s = this.stationNameJLabel.getText();
this.stationNameJLabel.setText(s + " (Priority Orders)");
}
// Check for 'No change'
if (null == trainOrders.order.consist) {
if (trainOrders.order.autoConsist) {
this.noChangeJLabel.setText("Select wagons automatically");
} else {
this.noChangeJLabel.setText("No Change");
}
} else {
this.noChangeJLabel.setText(null);
}
// Set the section title
// this.sectionTitleJLabel.setText("trainOrders.sectionTitle");
return this;
}

doMove

Class: jfreerails.move.WorldDiffMove

Documentation

No documentation available

Source Code

private void doMove(World world, boolean undo) {
for (int i = 0; i < diffs.size(); i++) {
MapDiff diff = diffs.get(i);
FreerailsSerializable tile = undo ? diff.before : diff.after;
world.setTile(diff.x, diff.y, tile);
}
}

testGetPoint

Class: jfreerails.world.train.TrainPositionOnMapTest

Documentation

No documentation available

Source Code

public void testGetPoint() {
TrainPositionOnMap a;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
assertEquals(a.getX(0), 10);
assertEquals(a.getY(0), 11);
assertEquals(a.getX(1), 20);
assertEquals(a.getY(1), 22);
}

paint

Class: jfreerails.client.renderer.BuildTrackRenderer

Documentation

/**
* Paints the proposed track and dots to distinguish the proposed track from
* any existing track.
*/

Source Code

/**
* Paints the proposed track and dots to distinguish the proposed track from
* any existing track.
*/
public void paint(Graphics2D g) {
WorldDiffs worldDiffs = getWorldDiffs();
if (null != worldDiffs) {
for (Iterator<ImPoint> iter = worldDiffs.getMapDiffs(); iter
.hasNext();) {
ImPoint point = iter.next();
FreerailsTile fp = (FreerailsTile)worldDiffs.getTile(point.x,
point.y);
TrackPiece tp = fp.getTrackPiece();
int graphicsNumber = tp.getTrackGraphicID();
int ruleNumber = tp.getTrackTypeID();
jfreerails.client.renderer.TrackPieceRenderer trackPieceView = rr
.getTrackPieceView(ruleNumber);
trackPieceView.drawTrackPieceIcon(graphicsNumber, g, point.x,
point.y, tileSize);
}
ReadOnlyWorld realWorld = modelRoot.getWorld();
/*
* Draw small dots for each tile whose track has changed. The dots
* are white if track has been added or upgraded and red if it has
* been removed.
*/
for (Iterator<ImPoint> iter = worldDiffs.getMapDiffs(); iter
.hasNext();) {
ImPoint p = iter.next();
int x = p.x * tileSize.width
+ (tileSize.width - SMALL_DOT_WIDTH) / 2;
int y = p.y * tileSize.width
+ (tileSize.height - SMALL_DOT_WIDTH) / 2;
FreerailsTile before = (FreerailsTile) realWorld.getTile(p.x,
p.y);
FreerailsTile after = (FreerailsTile) worldDiffs.getTile(p.x,
p.y);
boolean trackRemoved = !after.getTrackPiece().getTrackConfiguration().contains(
before.getTrackPiece().getTrackConfiguration());
Color dotColor = trackRemoved ? Color.RED : Color.WHITE;
g.setColor(dotColor);
g.fillOval(x, y, SMALL_DOT_WIDTH, SMALL_DOT_WIDTH);
}
}
}

BuildTrackExplorer

Class: jfreerails.controller.BuildTrackExplorer

Documentation

No documentation available

Source Code

public BuildTrackExplorer(ReadOnlyWorld w, FreerailsPrincipal principal) {
this(w, principal, null, new ImPoint(0, 0));
}

testRemoveLastD2

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List2DDiff.removeLastD2(int)'
*/
public void testRemoveLastD2() {
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
Object removed = diffs.removeLastD2(0);
assertEquals(String.valueOf(2), removed);
assertEquals(2, underlying.sizeD2(0));
assertEquals(2, diffs.getUnderlyingSize(0));
assertEquals(1, map.size());
assertEquals(1, diffs.sizeD2(0));
}

testGetLength

Class: jfreerails.world.train.TrainPositionOnMapTest

Documentation

No documentation available

Source Code

public void testGetLength() {
TrainPositionOnMap a;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20, 30, 40 },
new int[] { 11, 22, 33, 44 });
assertEquals(4, a.getLength());
}

setup

Class: jfreerails.client.view.View

Documentation

No documentation available

Source Code

void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction);

Called Methods

No outgoing method calls

nextTick

Class: jfreerails.world.common.GameTime

Documentation

No documentation available

Source Code

public GameTime nextTick() {
return new GameTime(ticks + 1);
}

Called Methods

No outgoing method calls

selectTileIcon

Class: jfreerails.client.renderer.RiverStyleTileRenderer

Documentation

No documentation available

Source Code

@Override
public int selectTileIcon(int x, int y, ReadOnlyWorld w) {
int iconNumber = 0;
for (int i = 0; i < 4; i++) {
iconNumber = iconNumber << 1;
iconNumber = iconNumber
| checkTile(x + X_LOOK_AT[i], y + Y_LOOK_AT[i], w);
}
return iconNumber;
}

removeLastD1

Class: jfreerails.util.List3DImpl

Documentation

No documentation available

Source Code

public void removeLastD1() {
int last = elementData.size()-1;
if(elementData.get(last).size() > 0)
throw new IllegalStateException(String.valueOf(last));
elementData.remove(last);
}

Called Methods

No outgoing method calls

CompressedOutputStream

Class: jfreerails.util.CompressedOutputStream

Documentation

No documentation available

Source Code

public CompressedOutputStream(OutputStream out) {
super(out);
buffer = new byte[0x7d000];
compBuffer = new byte[(int) (buffer.length * 1.2D)];
writeIndex = 0;
deflater = new Deflater(9);
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.util.List1DDiff

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return size();
}

toString

Class: jfreerails.world.common.ImInts

Documentation

No documentation available

Source Code

@Override
public String toString() {
StringBuffer sb = new StringBuffer(getClass().getName());
sb.append("[");
for (int i = 0; i < ints.length; i++) {
sb.append(ints[i]);
if (i + 1 < ints.length)
sb.append(", ");
}
sb.append("]");
return sb.toString();
}

Called Methods

No outgoing method calls

isKeepRunning

Class: jfreerails.network.InetConnectionAccepter

Documentation

No documentation available

Source Code

private boolean isKeepRunning() {
return keepRunning.isOpen();
}

VerifyStationName

Class: jfreerails.controller.VerifyStationName

Documentation

No documentation available

Source Code

public VerifyStationName(ReadOnlyWorld world, String name) {
this.w = world;
this.nameToVerify = name;
this.stationAlternatives = new Vector<String>();
stationAlternatives.addElement("Junction");
stationAlternatives.addElement("Siding");
stationAlternatives.addElement("North");
stationAlternatives.addElement("East");
stationAlternatives.addElement("South");
stationAlternatives.addElement("West");
}

Called Methods

No outgoing method calls

sizeD2

Class: jfreerails.util.List3DImpl

Documentation

No documentation available

Source Code

public int sizeD2(int d1) {
return elementData.get(d1).size();
}

Called Methods

No outgoing method calls

setEngineType

Class: jfreerails.client.view.SelectWagonsJPanel

Documentation

No documentation available

Source Code

public void setEngineType(int engineType) {
this.engineType = engineType;
}

Called Methods

No outgoing method calls

getSupply

Class: jfreerails.world.station.SupplyAtStation

Documentation

/**
* Returns the number of car loads of the specified cargo that the station
* supplies per year.
*/

Source Code

/**
* Returns the number of car loads of the specified cargo that the station
* supplies per year.
*/
public int getSupply(int cargoType) {
return supply.get(cargoType);
}

getGameSpeedDesc

Class: jfreerails.client.view.ServerControlModel

Documentation

/**
* Returns human readable string description of <code>tickPerSecond</code>
* number. Looks for <code>tickPerSecond</code> in
* <code>targetTicksPerSecondActions</code>. If appropriate action is not
* found returns first greater value or the greatest value.
*
* @param tickPerSecond
* int
* @return String human readable description
*/

Source Code

/**
* Returns human readable string description of <code>tickPerSecond</code>
* number. Looks for <code>tickPerSecond</code> in
* <code>targetTicksPerSecondActions</code>. If appropriate action is not
* found returns first greater value or the greatest value.
*
* @param tickPerSecond
* int
* @return String human readable description
*/
public String getGameSpeedDesc(int tickPerSecond) {
SetTargetTicksPerSecondAction action = null;
for (int i = 0; i < speedActions.length; i++) {
action = speedActions[i];
if (action.speed >= tickPerSecond)
break;
}
return (String) action.getValue(Action.NAME);
}

Called Methods

No outgoing method calls

TrackMoveTransactionsGenerator

Class: jfreerails.move.TrackMoveTransactionsGenerator

Documentation

/**
* @param p
* the Principal on behalf of which this object generates
* transactions for
*/

Source Code

/**
* @param p
* the Principal on behalf of which this object generates
* transactions for
*/
public TrackMoveTransactionsGenerator(ReadOnlyWorld world,
FreerailsPrincipal p) {
w = world;
principal = p;
}

Called Methods

No outgoing method calls

growCities

Class: jfreerails.server.CityTilePositioner

Documentation

No documentation available

Source Code

void growCities() {
final int numCities = w.size(SKEY.CITIES);
/*
* At some stage this will be refined to take into account how much
* cargo has been picked up and delivered and what city tiles are
* already present.
*/
for (int cityId = 0; cityId < numCities; cityId++) {
CityEconomicModel city = new CityEconomicModel();
city.loadFromMap(w, cityId);
// Only increase cities with stations and less than 16 tiles
if (city.size() < 16 && city.stations > 0) {
switch (random.nextInt(10)) {
case 0:
case 1:
addResourceTile(city); // 20% chance
break;
case 2:
case 3:
case 4:
case 5:
addUrbanTile(city); // 40% chance
break;
case 6:
addIndustryTile(city); // 10% chance
break;
default:
// do nothing, 30% chance
break;
}
city.write2map(w);
}
}
}

assertNoException

Class: jfreerails.world.common.PositionOnTrackTest

Documentation

No documentation available

Source Code

private void assertNoException(int x, int y, Step v) {
try {
PositionOnTrack.createComingFrom(x, y, v);
} catch (Exception e) {
assertTrue(false);
}
}

getFlatInstance

Class: jfreerails.world.track.TrackConfiguration

Documentation

No documentation available

Source Code

public static TrackConfiguration getFlatInstance(String trackTemplate) {
int i = TrackConfiguration.stringTemplate2Int(trackTemplate);
return (flatTrackConfigurations.get(i));
}

StationBuilder

Class: jfreerails.controller.StationBuilder

Documentation

No documentation available

Source Code

public StationBuilder(MoveExecutor executor) {
this.executor = executor;
TrackRule trackRule;
int i = -1;
ReadOnlyWorld world = executor.getWorld();
do {
i++;
trackRule = (TrackRule) world.get(SKEY.TRACK_RULES, i);
} while (!trackRule.isStation());
ruleNumber = i;
}

setupSearch

Class: jfreerails.controller.SimpleAStarPathFinder

Documentation

No documentation available

Source Code

public void setupSearch(int[] currentPosition, int[] targets,
GraphExplorer e) throws PathNotFoundException {
abandonSearch();
explorer = e;
// put the starting nodes on the open list (you can leave its f at zero)
for (int i = 0; i < targets.length; i++) {
openList.add(targets[i], 0);
for (int j = 0; j < currentPosition.length; j++) {
if (targets[i] == currentPosition[j]) {
status = PATH_NOT_FOUND;
throw new PathNotFoundException("Already at target!");
}
}
}
for (int j = 0; j < currentPosition.length; j++) {
startingPositions.add(currentPosition[j]);
}
}

getMapView

Class: jfreerails.client.view.MapViewJComponent

Documentation

No documentation available

Source Code

public MapRenderer getMapView() {
return mapView;
}

Called Methods

No outgoing method calls

GrowableBase

Class: jfreerails.util.GrowableBase

Documentation

/**
* Constructor with partial specification.
*
* @param size
* number of elements initially allowed in array
* @param type
* array element type
*/

Source Code

/**
* Constructor with partial specification.
*
* @param size
* number of elements initially allowed in array
* @param type
* array element type
*/
public GrowableBase(int size, Class type) {
this(size, Integer.MAX_VALUE, type);
}

hashCode

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = players.size();
return result;
}

getTransaction

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public Transaction getTransaction(FreerailsPrincipal p, int i) {
int playerIndex = p.getWorldIndex();
TransactionAndTimeStamp tats = bankAccounts.get(playerIndex, i);
return tats.getT();
}

testHit3

Class: jfreerails.client.renderer.TrainRendererTest

Documentation

No documentation available

Source Code

@Test
public void testHit3() {
Point wagonCenter = new Point(100, 100);
Point mouseClick = new Point(85, 100);
boolean hit = isHit(wagonCenter, mouseClick, Step.NORTH);
assertFalse(hit);
}

testEqualsBySerialization

Class: jfreerails.util.UtilsTest

Documentation

No documentation available

Source Code

public void testEqualsBySerialization() {
Serializable a = new Point(10, 10);
Serializable b = new Point(10, 10);
Serializable c = new Point(30, 10);
assertTrue(Utils.equalsBySerialization(a, b));
assertTrue(Utils.equalsBySerialization(a, a));
assertTrue(Utils.equalsBySerialization(b, b));
assertTrue(Utils.equalsBySerialization(c, c));
assertFalse(Utils.equalsBySerialization(a, c));
}

getConsumption

Class: jfreerails.world.terrain.NullTerrainType

Documentation

No documentation available

Source Code

public ImList<Consumption> getConsumption() {
return new ImList<Consumption>();
}

Called Methods

No outgoing method calls

setUp

Class: jfreerails.controller.StationBuilderTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
super.setUp();
w = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(w, 0);
ModelRoot mr = new ModelRootImpl();
trackBuilder = new TrackMoveProducer(me, w, mr);
stationBuilder = new StationBuilder(me);
}

RepaintManagerForActiveRendering

Class: jfreerails.client.common.RepaintManagerForActiveRendering

Documentation

No documentation available

Source Code

private RepaintManagerForActiveRendering() {
}

Called Methods

No outgoing method calls

fromServer

Class: jfreerails.network.specifics.MovePrecommitter

Documentation

No documentation available

Source Code

Move fromServer(PreMove pm) {
Move generatedMove = pm.generateMove(w);
fromServer(generatedMove);
return generatedMove;
}

RandomTerrainValue

Class: jfreerails.server.RandomTerrainValue

Documentation

No documentation available

Source Code

public RandomTerrainValue(int x, int y, int tt) {
this.x = x;
this.y = y;
this.terrainType = tt;
}

Called Methods

No outgoing method calls

readResolve

Class: jfreerails.controller.TimeTickPreMove

Documentation

No documentation available

Source Code

private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}

Called Methods

No outgoing method calls

actionPerformed

Class: jfreerails.client.view.Unknown

Documentation

No documentation available

Source Code

public void actionPerformed(ActionEvent arg0) {
showTrainList();
}

createOverviewMap

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

public JPanel createOverviewMap() {
return overviewMapContainer;
}

Called Methods

No outgoing method calls

suite

Class: jfreerails.world.track.TrackConfigurationTest

Documentation

No documentation available

Source Code

public static Test suite() {
TestSuite suite = new TestSuite(TrackConfigurationTest.class);
return suite;
}

Called Methods

No outgoing method calls

HtmlJPanel

Class: jfreerails.client.view.HtmlJPanel

Documentation

No documentation available

Source Code

public HtmlJPanel(URL url, HashMap context) {
initComponents();
String template = loadText(url);
String populatedTemplate = populateTokens(template, context);
setHtml(populatedTemplate);
}

sizeD1

Class: jfreerails.util.List3D

Documentation

No documentation available

Source Code

int sizeD1();

Called Methods

No outgoing method calls

SoundManager

Class: jfreerails.client.common.SoundManager

Documentation

No documentation available

Source Code

private SoundManager() {
AudioFormat format2 = new AudioFormat(8000f, 16, 1, true, false);
DataLine.Info info2 = new DataLine.Info(Clip.class, format2);
for (Mixer.Info mo : AudioSystem.getMixerInfo()) {
mixer = AudioSystem.getMixer(mo);
maxLines = mixer.getMaxLines(info2);
if (maxLines == AudioSystem.NOT_SPECIFIED){
maxLines = 100;
}
if (maxLines >= 32)
break; // Java Sound Audio Engine, version 1.0 satisfies this.
}
logger.fine("Sound Mixer: " + mixer.getMixerInfo() + "(" + maxLines
+ " voices).");
}

Called Methods

No outgoing method calls

add

Class: jfreerails.world.track.TrackConfiguration

Documentation

/**
* @return the superposition of two track templates
*/

Source Code

/**
* @return the superposition of two track templates
*/
public static TrackConfiguration add(FlatTrackTemplate c,
FlatTrackTemplate v) {
/*
* int x=v.getX()+1; int y=v.getY()+1; int oldTemplate
* =c.getTrackGraphicsNumber(); int newTemplate = oldTemplate | (1 <<
* (3 * y + x));
*/
int newTemplate = c.get9bitTemplate() | v.get9bitTemplate();
return from9bitTemplate(newTemplate);
}

enableButtons

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void enableButtons() {
MutableSchedule s = getSchedule();
addStationJButton.setEnabled(s.canAddOrder());
// Only one set of priority orders are allowed.
priorityOrdersJButton.setEnabled(!s.hasPriorityOrders());
}

getScrollableUnitIncrement

Class: jfreerails.client.view.MapViewJComponent

Documentation

No documentation available

Source Code

public int getScrollableUnitIncrement(java.awt.Rectangle rectangle,
int orientation, int direction) {
return (int) getMapView().getScale();
}

equals

Class: jfreerails.world.station.SupplyAtStation

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof SupplyAtStation))
return false;
final SupplyAtStation supplyAtStation = (SupplyAtStation) o;
if (!supply.equals(supplyAtStation.supply))
return false;
return true;
}

set

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public void set(ITEM item, FreerailsSerializable element) {
items.set(item.getKeyID(), element);
}

testCalculateNumberOfEachTrackType

Class: jfreerails.server.TrackMaintenanceMoveGeneratorTest

Documentation

No documentation available

Source Code

public void testCalculateNumberOfEachTrackType() {
int[] actual;
int[] expected;
actual = calNumOfEachTrackType();
/*
* actual = ItemsTransactionAggregator.calulateNumberOfEachTrackType(w,
* MapFixtureFactory.TEST_PRINCIPAL, 0);
*/
expected = new int[] { 0, 0, 0 }; // No track has been built yet.
assertTrue(Arrays.equals(expected, actual));
addTrack(0, 10);
actual = calNumOfEachTrackType();
expected = new int[] { 10, 0, 0 };
assertTrue(Arrays.equals(expected, actual));
addTrack(2, 20);
actual = calNumOfEachTrackType();
expected = new int[] { 10, 0, 20 };
assertTrue(Arrays.equals(expected, actual));
}

getX

Class: jfreerails.server.RandomTerrainValue

Documentation

No documentation available

Source Code

public int getX() {
return x;
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.move.ChangeGameSpeedMove

Documentation

No documentation available

Source Code

@Override
public String toString() {
return "ChangeGameSpeedMove: " + oldSpeed + "=>" + newSpeed;
}

Called Methods

No outgoing method calls

ordersMouseClicked

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void ordersMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_ordersMouseClicked
int i = orders.getSelectedIndex();
MutableSchedule s = getSchedule();
if (i >= s.getNumOrders()) {
// The selected index does not exist!
// For some reason, the JList hasn't updated yet.
i = -1;
}
if (-1 != i && java.awt.event.MouseEvent.BUTTON3 == evt.getButton()) {
// If an element is select and the right button is pressed.
TrainOrdersModel order = s.getOrder(i);
pullUpJMenuItem.setEnabled(s.canPullUp(i));
pushDownJMenuItem.setEnabled(s.canPushDown(i));
gotoStationJMenuItem.setEnabled(s.canSetGotoStation(i));
removeWagonsJMenu.setEnabled(order.orderHasWagons());
waitJMenu.setEnabled(order.orderHasWagons());
addWagonJMenu.setEnabled(order.hasLessThanMaximumNumberOfWagons());
setupWagonsPopup();
this.editOrderJPopupMenu.show(evt.getComponent(), evt.getX(), evt
.getY());
}
}// GEN-LAST:event_ordersMouseClicked

paintRect

Class: jfreerails.client.view.MapViewJComponentConcrete

Documentation

No documentation available

Source Code

public void paintRect(Graphics g, Rectangle visibleRect) {
throw new UnsupportedOperationException();
}

Called Methods

No outgoing method calls

setTile

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public void setTile(int x, int y, FreerailsSerializable element) {
map[x][y] = element;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.top.GameRules

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = (canConnect2OtherRRTrack ? 1 : 0);
result = 29 * result + (mustConnect2ExistingTrack ? 1 : 0);
return result;
}

Called Methods

No outgoing method calls

writeToServer

Class: jfreerails.network.InetConnection2Server

Documentation

No documentation available

Source Code

public void writeToServer(FreerailsSerializable object) throws IOException {
send(object);
}

getMoves

Class: jfreerails.controller.TrainStopsHandler

Documentation

No documentation available

Source Code

public Move getMoves() {
Move m = WorldDiffMove.generate(worldDiffs, WorldDiffMove.Cause.TrainArrives);
worldDiffs.reset();
return m;
}

SaveGameMessage2Server

Class: jfreerails.network.specifics.SaveGameMessage2Server

Documentation

No documentation available

Source Code

public SaveGameMessage2Server(int id, String s) {
this.id = id;
this.filename = s;
}

Called Methods

No outgoing method calls

getQuantity

Class: jfreerails.world.accounts.AddItemTransaction

Documentation

No documentation available

Source Code

public int getQuantity() {
return quantity;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.move.WorldDiffMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = diffs.hashCode();
result = 29 * result + x;
result = 29 * result + y;
result = 29 * result + w;
result = 29 * result + h;
return result;
}

format

Class: jfreerails.client.common.BinaryNumberFormatter

Documentation

No documentation available

Source Code

public static String format(int i, int bits) {
int maxValue = 1 << (bits);
if (i < 0) {
throw new IllegalArgumentException(
"i must be greater than 0. It was " + i);
}
if (i >= maxValue) {
throw new IllegalArgumentException("i must be less than "
+ maxValue + ". It was " + i);
}
String s = Integer.toString(i + maxValue, 2);
String number = s.substring(1);
return number;
}

Called Methods

No outgoing method calls

sizeD3

Class: jfreerails.util.List3D

Documentation

No documentation available

Source Code

int sizeD3(int d1, int d2);

Called Methods

No outgoing method calls

hasTrack

Class: jfreerails.world.track.FreerailsTile

Documentation

No documentation available

Source Code

public boolean hasTrack(){
return trackPiece.getTrackTypeID() != NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER;
}

setProperty

Class: jfreerails.launcher.GUIClient

Documentation

No documentation available

Source Code

@Override
public void setProperty(ClientProperty propertyName, Serializable value) {
super.setProperty(propertyName, value);
switch (propertyName) {
case SAVED_GAMES:
modelRoot.setProperty(Property.SAVED_GAMES_LIST, value);
break;
default:
break;
}
}

getStartTime

Class: jfreerails.world.common.ActivityIterator

Documentation

/** Returns the time the current activity starts. */

Source Code

/** Returns the time the current activity starts. */
double getStartTime();

Called Methods

No outgoing method calls

testMove2

Class: jfreerails.move.ChangeTileMoveTest

Documentation

No documentation available

Source Code

public void testMove2() {
Point p = new Point(10, 10);
ChangeTileMove move = new ChangeTileMove(world, p, 5);
assertSurvivesSerialisation(move);
}

testBuildStation

Class: jfreerails.controller.StationBuilderTest

Documentation

No documentation available

Source Code

public void testBuildStation() {
stationBuilder
.setStationType(stationBuilder.getTrackTypeID("terminal"));
Step[] track = { EAST, EAST, EAST };
MoveStatus ms = trackBuilder.buildTrack(new ImPoint(10, 10), track);
assertTrue(ms.ok);
assertTrue(stationBuilder.tryBuildingStation(new ImPoint(10, 10)).ok);
assertTrue(stationBuilder.tryBuildingStation(new ImPoint(13, 10)).ok);
MoveStatus ms1 = stationBuilder.buildStation(new ImPoint(10, 10));
assertTrue(ms1.ok);
MoveStatus ms2 = stationBuilder.buildStation(new ImPoint(13, 10));
assertFalse(ms2.ok);
}

getUpdatedTiles

Class: jfreerails.move.ChangeTrackPieceCompositeMove

Documentation

No documentation available

Source Code

public Rectangle getUpdatedTiles() {
return new Rectangle(x, y, w, h);
}

Called Methods

No outgoing method calls

setupWorld

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

protected void setupWorld() {
setWorld(new WorldImpl(10, 10));
// Set the time..
getWorld().set(ITEM.CALENDAR, new GameCalendar(12000, 1840));
getWorld().addPlayer(MapFixtureFactory.TEST_PLAYER);
}

SimplePathIteratorImpl

Class: jfreerails.world.train.SimplePathIteratorImpl

Documentation

No documentation available

Source Code

public SimplePathIteratorImpl(ImInts xpoints, ImInts ypoints) {
x = xpoints;
y = ypoints;
if (x.size() != y.size()) {
throw new IllegalArgumentException(
"The array length of the array must be even");
}
}

getRotations

Class: jfreerails.world.track.EightRotationsOfTrackPieceProducer

Documentation

/**
* The method that returns the rotations.
*
* @param trackBlueprint
* A 9bit value that serves as the template.
* @return An array of 8 9-bit values that have been generated by rotating
* the template.
*/

Source Code

/**
* The method that returns the rotations.
*
* @param trackBlueprint
* A 9bit value that serves as the template.
* @return An array of 8 9-bit values that have been generated by rotating
* the template.
*/
public static int[] getRotations(int trackBlueprint) {
int trackTemplate = trackBlueprint;
int[] derivedTrackPieces = new int[8];
for (int i = 0; i < 8; i++) {
derivedTrackPieces[i] = trackTemplate;
boolean[][] trackTemplateBooleanArray = getTrackBooleanArray(trackTemplate);
trackTemplateBooleanArray = rotateTrackNodeClockwise(trackTemplateBooleanArray);
trackTemplate = getTrackGraphicID(trackTemplateBooleanArray);
}
return derivedTrackPieces;
}

setup

Class: jfreerails.client.view.TrainDialogueJPanel

Documentation

No documentation available

Source Code

public void setup(ModelRoot mr, RenderersRoot vl, Action al) {
newTrainScheduleJPanel1.setup(mr, vl, al);
trainDetailsJPanel1.setup(mr, vl, al);
this.setCancelButtonActionListener(al);
this.principal = mr.getPrincipal();
this.w = mr.getWorld();
}

tryUndoMove

Class: jfreerails.move.ChangeGameSpeedMove

Documentation

No documentation available

Source Code

public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
GameSpeed speed = ((GameSpeed) w.get(ITEM.GAME_SPEED));
if (speed.equals(newSpeed)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + newSpeed + ", found "
+ speed);
}

getWorld

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

World getWorld() {
return world;
}

Called Methods

No outgoing method calls

undoMove

Class: jfreerails.move.ChangeGameSpeedMove

Documentation

No documentation available

Source Code

public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryUndoMove(w, p);
if (status.isOk()) {
w.set(ITEM.GAME_SPEED, oldSpeed);
}
return status;
}

World2ListModelAdapter

Class: jfreerails.client.view.World2ListModelAdapter

Documentation

No documentation available

Source Code

public World2ListModelAdapter(ReadOnlyWorld world, SKEY key) {
this.w = world;
if (null == key)
throw new NullPointerException();
if (null == w)
throw new NullPointerException();
elements = new NonNullElements(key, world);
}

Called Methods

No outgoing method calls

StandardTileRenderer

Class: jfreerails.client.renderer.StandardTileRenderer

Documentation

No documentation available

Source Code

public StandardTileRenderer(ImageManager imageManager, int[] rgbValues,
TerrainType tileModel) throws IOException {
super(tileModel, rgbValues);
this.setTileIcons(new Image[1]);
this.getTileIcons()[0] = imageManager.getImage(generateFilename());
}

getPlayer

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public Player getPlayer(int i) {
return players.get(i);
}

buildTrack

Class: jfreerails.controller.TrackMoveProducer

Documentation

No documentation available

Source Code

public MoveStatus buildTrack(ImPoint from, Step trackVector) {
ReadOnlyWorld w = executor.getWorld();
FreerailsPrincipal principal = executor.getPrincipal();
switch (getBuildMode()) {
case IGNORE_TRACK: {
return MoveStatus.MOVE_OK;
}
case REMOVE_TRACK: {
try {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateRemoveTrackMove(from, trackVector, w,
principal);
Move moveAndTransaction = transactionsGenerator
.addTransactions(move);
return sendMove(moveAndTransaction);
} catch (Exception e) {
// thrown when there is no track to remove.
// Fix for bug [ 948670 ] Removing non-existent track
return MoveStatus.moveFailed("No track to remove.");
}
}
case BUILD_TRACK:
case UPGRADE_TRACK:
/*
* Do nothing yet since we need to work out what type of track to
* build.
*/
break;
}
assert (getBuildMode() == BuildMode.BUILD_TRACK || getBuildMode() == BuildMode.UPGRADE_TRACK);
int[] ruleIDs = new int[2];
TrackRule[] rules = new TrackRule[2];
int[] xs = { from.x, from.x + trackVector.deltaX };
int[] ys = { from.y, from.y + trackVector.deltaY };
for (int i = 0; i < ruleIDs.length; i++) {
int x = xs[i];
int y = ys[i];
FreerailsTile tile = (FreerailsTile) w.getTile(x, y);
int tt = tile.getTerrainTypeID();
ruleIDs[i] = getBuildTrackStrategy().getRule(tt);
if (ruleIDs[i] == -1) {
TerrainType terrainType = (TerrainType) w.get(
SKEY.TERRAIN_TYPES, tt);
String message = "Non of the selected track types can be built on "
+ terrainType.getDisplayName();
return MoveStatus.moveFailed(message);
}
rules[i] = (TrackRule) w.get(SKEY.TRACK_RULES, ruleIDs[i]);
}
switch (getBuildMode()) {
case UPGRADE_TRACK: {
// upgrade the from tile if necessary.
FreerailsTile tileA = (FreerailsTile) w.getTile(from.x, from.y);
if (tileA.getTrackPiece().getTrackTypeID() != ruleIDs[0] && !isStationHere(from)) {
MoveStatus ms = upgradeTrack(from, ruleIDs[0]);
if (!ms.ok) {
return ms;
}
}
ImPoint point = new ImPoint(from.x + trackVector.getDx(), from.y
+ trackVector.getDy());
FreerailsTile tileB = (FreerailsTile) w.getTile(point.x, point.y);
if (tileB.getTrackPiece().getTrackTypeID() != ruleIDs[1] && !isStationHere(point)) {
MoveStatus ms = upgradeTrack(point, ruleIDs[1]);
if (!ms.ok) {
return ms;
}
}
return MoveStatus.MOVE_OK;
}
case BUILD_TRACK: {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(from, trackVector, rules[0],
rules[1], w, principal);
Move moveAndTransaction = transactionsGenerator
.addTransactions(move);
return sendMove(moveAndTransaction);
}
default:
throw new IllegalArgumentException(String.valueOf(getBuildMode()));
}
}

testCanRemoveFromTail

Class: jfreerails.world.train.TrainPositionOnMapTest

Documentation

No documentation available

Source Code

public void testCanRemoveFromTail() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20, 40, 50 },
new int[] { 11, 22, 44, 55 });
b = TrainPositionOnMap.createInstance(new int[] { 10, 20, 30 },
new int[] { 11, 22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 30, 40, 50 },
new int[] { 33, 44, 55 });
assertTrue(!b.canRemoveFromTail(a));
assertTrue(!a.canRemoveFromTail(b));
assertTrue(!c.canRemoveFromTail(b));
assertTrue(!b.canRemoveFromTail(c));
assertTrue(!c.canRemoveFromTail(a));
assertTrue(a.canRemoveFromTail(c));
}

createDisplayMenu

Class: jfreerails.client.top.GUIComponentFactoryTestImpl

Documentation

No documentation available

Source Code

public JMenu createDisplayMenu() {
return displayMenu;
}

Called Methods

No outgoing method calls

generateBuildTrackMove

Class: jfreerails.move.ChangeTrackPieceCompositeMove

Documentation

No documentation available

Source Code

public static ChangeTrackPieceCompositeMove generateBuildTrackMove(
ImPoint from, Step direction, TrackRule ruleA, TrackRule ruleB,
ReadOnlyWorld w, FreerailsPrincipal principal) {
ChangeTrackPieceMove a;
ChangeTrackPieceMove b;
a = getBuildTrackChangeTrackPieceMove(from, direction, ruleA, w,
principal);
b = getBuildTrackChangeTrackPieceMove(direction
.createRelocatedPoint(from), direction.getOpposite(), ruleB, w,
principal);
return new ChangeTrackPieceCompositeMove(a, b, principal);
}

getIndex

Class: jfreerails.move.AddItemToSharedListMove

Documentation

No documentation available

Source Code

public int getIndex() {
return index;
}

Called Methods

No outgoing method calls

setUp

Class: jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
// Set up the world object with three cargo types, one station, and one
// train.
w = new WorldImpl();
w.addPlayer(MapFixtureFactory.TEST_PLAYER);
// set up the cargo types.
w.add(SKEY.CARGO_TYPES, new CargoType(0, "Mail", Categories.Mail));
w.add(SKEY.CARGO_TYPES, new CargoType(0, "Passengers",
Categories.Passengers));
w.add(SKEY.CARGO_TYPES, new CargoType(0, "Goods",
Categories.Fast_Freight));
// Set up station
int x = 10;
int y = 10;
int stationCargoBundleId = w.add(MapFixtureFactory.TEST_PRINCIPAL,
KEY.CARGO_BUNDLES,
ImmutableCargoBundle.EMPTY_BUNDLE);
String stationName = "Station 1";
StationModel station = new StationModel(x, y, stationName, w
.size(SKEY.CARGO_TYPES), stationCargoBundleId);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, station);
// Set up train
int trainCargoBundleId = w.add(MapFixtureFactory.TEST_PRINCIPAL,
KEY.CARGO_BUNDLES,
ImmutableCargoBundle.EMPTY_BUNDLE);
// 3 wagons to carry cargo type 0.
ImInts wagons = new ImInts(0, 0, 0);
TrainModel train = new TrainModel(wagons, trainCargoBundleId);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.TRAINS, train);
}

setUp

Class: jfreerails.world.top.NonNullElementsTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() {
w = new WorldImpl();
station1 = new StationModel(10, 20, "Station1", 4, 0);
station2 = new StationModel(15, 16, "Station2", 4, 1);
station3 = new StationModel(30, 50, "Station3", 4, 2);
w.addPlayer(MapFixtureFactory.TEST_PLAYER);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, station1);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, null);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, station2);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, null);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, null);
w.add(MapFixtureFactory.TEST_PRINCIPAL, KEY.STATIONS, station3);
}

populateTokens

Class: jfreerails.client.view.BrokerJFrame

Documentation

No documentation available

Source Code

public String populateTokens(String template, Object context) {
StringTokenizer tokenizer = new StringTokenizer(template, "$");
String output = "";
while (tokenizer.hasMoreTokens()) {
output += tokenizer.nextToken();
if (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
String value;
if (context instanceof HashMap) {
value = (String) ((HashMap) context).get(token);
} else {
try {
Field field = context.getClass().getField(token);
value = field.get(context).toString();
} catch (Exception e) {
e.printStackTrace();
throw new NoSuchElementException(token);
}
}
output += value;
}
}
return output;
}

Called Methods

No outgoing method calls

ChangeTrackPieceCompositeMove

Class: jfreerails.move.ChangeTrackPieceCompositeMove

Documentation

No documentation available

Source Code

private ChangeTrackPieceCompositeMove(TrackMove a, TrackMove b,
FreerailsPrincipal fp) {
super(a, b);
Rectangle r = a.getUpdatedTiles().union(b.getUpdatedTiles());
x = r.x;
y = r.y;
w = r.width;
h = r.height;
builder = fp;
}

getFixedCost

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

public Money getFixedCost() {
return Money.ZERO;
}

Called Methods

No outgoing method calls

canPushDown

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public boolean canPushDown(int orderNumber) {
boolean isOrderPriorityOrders = (orderNumber == 0 && this.hasPriorityOrders);
boolean isAlreadyAtBottom = orderNumber == this.orders.size() - 1;
return !isOrderPriorityOrders && !isAlreadyAtBottom;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.world.player.WorldPrincipal

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return principalName.hashCode();
}

Called Methods

No outgoing method calls

selectEngineActionPerformed

Class: experimental.DialogueBoxTester

Documentation

No documentation available

Source Code

private void selectEngineActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_selectEngineActionPerformed
// Add your handling code here:
dialogueBoxController.showSelectEngine();
}// GEN-LAST:event_selectEngineActionPerformed

hashCode

Class: jfreerails.world.track.NullTrackPiece

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return 777;
}

Called Methods

No outgoing method calls

init

Class: jfreerails.client.view.StationPlacementCursor

Documentation

No documentation available

Source Code

private void init() {
if (buildEnabled) {
mapView.addMouseListener(this);
mapView.addMouseMotionListener(this);
stationRadiusRenderer.show();
} else {
stationRadiusRenderer.hide();
mapView.removeMouseListener(this);
mapView.removeMouseMotionListener(this);
}
stationBuildModel.getStationBuildAction().addPropertyChangeListener(
buildActionListener);
}

testAdd

Class: jfreerails.util.List1DDiffsTest

Documentation

No documentation available

Source Code

public void testAdd(){
Player player0 = new Player("player0", 0);
Player player1 = new Player("player1", 1);
int i = diffs.add(player0);
assertEquals(0, i);
assertEquals(1, diffs.size());
assertEquals(player0, diffs.get(0));
i = diffs.add(player1);
assertEquals(1, i);
assertEquals(2, diffs.size());
assertEquals(player1, diffs.get(1));
}

addD3

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

public int addD3(int d1, int d2, T element) {
return super.addElement(element, d1, d2);
}

BuildTrackRenderer

Class: jfreerails.client.renderer.BuildTrackRenderer

Documentation

No documentation available

Source Code

public BuildTrackRenderer(RenderersRoot trackPieceViewList,
ModelRoot modelRoot) {
this.modelRoot = modelRoot;
this.rr = trackPieceViewList;
}

Called Methods

No outgoing method calls

paintRect

Class: jfreerails.client.renderer.Unknown

Documentation

No documentation available

Source Code

public void paintRect(Graphics g, Rectangle visibleRect) {
}

Called Methods

No outgoing method calls

suite

Class: jfreerails.world.top.NonNullElementsTest

Documentation

No documentation available

Source Code

public static Test suite() {
TestSuite testSuite = new TestSuite(NonNullElementsTest.class);
return testSuite;
}

Called Methods

No outgoing method calls

abandonSearch

Class: jfreerails.controller.PathOnTrackFinder

Documentation

No documentation available

Source Code

public void abandonSearch() {
pathFinder.abandonSearch();
}

equals

Class: jfreerails.world.player.PlayerPrincipal

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (!(o instanceof PlayerPrincipal)) {
return false;
}
return id == ((PlayerPrincipal) o).id;
}

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.view.RHSJTabPane

Documentation

No documentation available

Source Code

public void setup(final ActionRoot actionRoot, RenderersRoot vl,
final ModelRootImpl modelRoot) {
world = modelRoot.getWorld();
terrainInfoPanel.setup(world, vl);
stationInfoPanel.setup(modelRoot, vl, null);
ActionListener showTrain = new ActionListener() {
public void actionPerformed(ActionEvent e) {
int id = trainListPanel.getSelectedTrainID();
actionRoot.getDialogueBoxController().showTrainOrders(id);
}
};
trainListPanel.setShowTrainDetailsActionListener(showTrain);
trainListPanel.setup(modelRoot, vl, null);
modelRoot.addPropertyChangeListener(this);
buildTrackPanel.setup(modelRoot, actionRoot, vl, null);
}

getMaximumConsecutivePieces

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

public int getMaximumConsecutivePieces() {
return legalConfigurations.getMaximumConsecutivePieces();
}

hashCode

Class: jfreerails.world.station.ConvertedAtStation

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result = 0;
for (int i = 0; i < convertedTo.size(); i++) {
result = 29 * result + convertedTo.get(i);
}
return result;
}

TrainListJPanel

Class: jfreerails.client.view.TrainListJPanel

Documentation

/** Creates new form TrainListJPanel. */

Source Code

/** Creates new form TrainListJPanel. */
public TrainListJPanel() {
initComponents();
}

currentTrainTarget

Class: jfreerails.controller.MoveTrainPreMove

Documentation

No documentation available

Source Code

private ImPoint currentTrainTarget(ReadOnlyWorld w) {
TrainAccessor ta = new TrainAccessor(w, principal, trainID);
return ta.getTarget();
}

abandonSearch

Class: jfreerails.controller.TrackPathFinder

Documentation

No documentation available

Source Code

public void abandonSearch() {
pathFinder.abandonSearch();
}

getCityX

Class: jfreerails.world.terrain.CityModel

Documentation

No documentation available

Source Code

public int getCityX() {
return x;
}

Called Methods

No outgoing method calls

ITEM

Class: jfreerails.world.top.ITEM

Documentation

No documentation available

Source Code

private ITEM() {
this.keyNumber = numberOfKeys;
keys[keyNumber] = this;
numberOfKeys++;
}

Called Methods

No outgoing method calls

stop

Class: jfreerails.network.GameServer

Documentation

No documentation available

Source Code

void stop();

Called Methods

No outgoing method calls

buildTrack

Class: jfreerails.controller.TrackMoveProducer

Documentation

No documentation available

Source Code

public MoveStatus buildTrack(ImPoint from, Step[] path) {
MoveStatus returnValue = MoveStatus.MOVE_OK;
int x = from.x;
int y = from.y;
for (int i = 0; i < path.length; i++) {
returnValue = buildTrack(new ImPoint(x, y), path[i]);
x += path[i].deltaX;
y += path[i].deltaY;
if (!returnValue.ok) {
return returnValue;
}
}
return returnValue;
}

setup

Class: jfreerails.client.view.CargoWaitingAndDemandedJPanel

Documentation

No documentation available

Source Code

public void setup(ModelRoot model, RenderersRoot vl,
Action closeAction) {
this.world = model.getWorld();
this.principal = model.getPrincipal();
}

writeAllImages

Class: jfreerails.client.common.ImageManager

Documentation

No documentation available

Source Code

void writeAllImages() throws IOException;

Called Methods

No outgoing method calls

findConstantFieldName

Class: jfreerails.util.Utils

Documentation

No documentation available

Source Code

public static String findConstantFieldName(Object o) {
Field[] fields = o.getClass().getFields();
for (int i = 0; i < fields.length; i++) {
int modifiers = fields[i].getModifiers();
try {
if (Modifier.isStatic(modifiers)
&& Modifier.isPublic(modifiers)) {
Object o2 = fields[i].get(null);
if (o2.equals(o)) {
return fields[i].getName();
}
}
} catch (IllegalAccessException e) {
throw new IllegalStateException();
}
}
return null;
}

Called Methods

No outgoing method calls

overallRate

Class: jfreerails.util.FlowRateOutputStream

Documentation

No documentation available

Source Code

public int overallRate() throws IOException {
return (int) (totalByteSent / 1024D / ((System.currentTimeMillis() - openTimeMillis) / 1000D));
}

Called Methods

No outgoing method calls

cancelProposedBuild

Class: jfreerails.client.top.UserInputOnMapController

Documentation

No documentation available

Source Code

private void cancelProposedBuild() {
ignoreDragging = true;
buildTrack.hide();
StationBuildModel sbm = actionRoot.getStationBuildModel();
sbm.getStationCancelAction().actionPerformed(
new ActionEvent(this, ActionEvent.ACTION_PERFORMED, ""));
setIgnoreKeyEvents(false);
}

addSkipPrefix

Class: jfreerails.util.ClassLocater

Documentation

/**
* Adds a prefix for classes (and packages) to completely ignore, based on
* their package + class name.
* <p>
* For example, "org.apache.log4j".
* <P>
* The advantage of this method is that you don't have to bother with regex
* syntax. Also, it is remembered between calls to getSubclassesOf - so it's
* useful if you know you never care about certain packages.
*
* @param s
* prefix of fully qualified class names to ignore
*/

Source Code

/**
* Adds a prefix for classes (and packages) to completely ignore, based on
* their package + class name.
* <p>
* For example, "org.apache.log4j".
* <P>
* The advantage of this method is that you don't have to bother with regex
* syntax. Also, it is remembered between calls to getSubclassesOf - so it's
* useful if you know you never care about certain packages.
*
* @param s
* prefix of fully qualified class names to ignore
*/
public void addSkipPrefix(String s) {
skipPrefixes.add(s);
}

Called Methods

No outgoing method calls

getTypeName

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

public String getTypeName() {
return "NullTrackType";
}

Called Methods

No outgoing method calls

getTrackPieceIcon

Class: jfreerails.client.renderer.NullTrackPieceRenderer

Documentation

No documentation available

Source Code

/*
* @see TrackPieceView#getTrackPieceIcon(int)
*/
public Image getTrackPieceIcon(int trackTemplate) {
return null;
}

Called Methods

No outgoing method calls

TrackRuleImpl

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

/*
* Track templates are 9 bit values, so there are 512 possible templates. If
* legalTrackTemplate[x]==true, then x is a legal track-template. Example:
* 000 111 000 This represents a horizontal straight.
*/
public TrackRuleImpl(TrackRuleProperties p, LegalTrackConfigurations lc,
LegalTrackPlacement ltp) {
if (null == p || null == lc || null == ltp) {
throw new java.lang.IllegalArgumentException();
}
properties = p;
legalConfigurations = lc;
legalTrackPlacement = ltp;
}

Called Methods

No outgoing method calls

size

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

/**
* Returns number of active entities belonging to the specified principal.
*/

Source Code

/**
* Returns number of active entities belonging to the specified principal.
*/
int size(FreerailsPrincipal p);

Called Methods

No outgoing method calls

getSourceX

Class: jfreerails.world.cargo.CargoBatch

Documentation

No documentation available

Source Code

public int getSourceX() {
return sourceX;
}

Called Methods

No outgoing method calls

findTrackRule

Class: jfreerails.controller.CalcCargoSupplyRateAtStation

Documentation

No documentation available

Source Code

private static int findTrackRule(int xx, int yy, ReadOnlyWorld w) {
FreerailsTile tile = (FreerailsTile) w.getTile(xx, yy);
int ruleNumber = tile.getTrackPiece().getTrackTypeID();
return ruleNumber;
}

doMove

Class: jfreerails.move.ChangeGameSpeedMove

Documentation

No documentation available

Source Code

public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus status = tryDoMove(w, p);
if (status.ok) {
w.set(ITEM.GAME_SPEED, newSpeed);
}
return status;
}

getNewSpeed

Class: jfreerails.move.ChangeGameSpeedMove

Documentation

No documentation available

Source Code

public int getNewSpeed() {
return newSpeed.getSpeed();
}

validate

Class: jfreerails.client.renderer.TileRendererList

Documentation

/**
* Checks whether this tile view list has tile views for all the terrain
* types in the specified list.
*/

Source Code

/**
* Checks whether this tile view list has tile views for all the terrain
* types in the specified list.
*/
boolean validate(ReadOnlyWorld world);

Called Methods

No outgoing method calls

getCityY

Class: jfreerails.world.terrain.CityModel

Documentation

No documentation available

Source Code

public int getCityY() {
return y;
}

Called Methods

No outgoing method calls

TrainDialogueJPanel

Class: jfreerails.client.view.TrainDialogueJPanel

Documentation

No documentation available

Source Code

public TrainDialogueJPanel() {
initComponents();
}

end_Tiles

Class: jfreerails.server.parser.Track_TilesHandlerImpl

Documentation

No documentation available

Source Code

public void end_Tiles() throws SAXException {
// Sort the track tiles by category then price.
Collections.sort(ruleList);
}

Called Methods

No outgoing method calls

testCanAddToTail

Class: jfreerails.world.train.TrainPositionOnMapTest

Documentation

No documentation available

Source Code

public void testCanAddToTail() {
TrainPositionOnMap a;
TrainPositionOnMap b;
TrainPositionOnMap c;
a = TrainPositionOnMap.createInstance(new int[] { 10, 20 }, new int[] {
11, 22 });
b = TrainPositionOnMap.createInstance(new int[] { 20, 30 }, new int[] {
22, 33 });
c = TrainPositionOnMap.createInstance(new int[] { 30, 40 }, new int[] {
33, 44 });
assertTrue(!b.canAddToTail(a));
assertTrue(a.canAddToTail(b));
assertTrue(!c.canAddToTail(b));
assertTrue(b.canAddToTail(c));
assertTrue(!c.canAddToTail(a));
assertTrue(!a.canAddToTail(c));
}

addInvalidComponent

Class: jfreerails.client.common.RepaintManagerForActiveRendering

Documentation

No documentation available

Source Code

@Override
public synchronized void addInvalidComponent(JComponent invalidComponent) {
if (hasDifferentAncestor(invalidComponent)) {
super.addInvalidComponent(invalidComponent);
} else {
numRepaintRequests++;
}
}

main

Class: experimental.GenerateDependenciesXmlAndHtml

Documentation

No documentation available

Source Code

public static void main(String[] args) {
try {
new GenerateDependenciesXmlAndHtml("checkdep.xml", "src"
+ File.separator + "docs" + File.separator
+ "dependencies.html");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

Called Methods

No outgoing method calls

undoMove

Class: jfreerails.move.AddItemToSharedListMove

Documentation

No documentation available

Source Code

public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.isOk()) {
w.removeLast(listKey);
}
return ms;
}

UpgradeTrackMove

Class: jfreerails.move.UpgradeTrackMove

Documentation

No documentation available

Source Code

private UpgradeTrackMove(ChangeTrackPieceMove trackMove) {
super(trackMove);
}

closebuttonActionPerformed

Class: jfreerails.controller.UnexpectedExceptionForm

Documentation

No documentation available

Source Code

private void closebuttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closebuttonActionPerformed
System.exit(1);
}//GEN-LAST:event_closebuttonActionPerformed

Called Methods

No outgoing method calls

addWagon

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void addWagon(int wagonTypeNumber) {
TrainOrdersModel oldOrders, newOrders;
MutableSchedule s = getSchedule();
int orderNumber = this.orders.getSelectedIndex();
oldOrders = s.getOrder(orderNumber);
int[] newConsist;
// The consist will be null if old orders were 'no change'.
if (null != oldOrders.consist) {
int oldLength = oldOrders.consist.size();
newConsist = new int[oldLength + 1];
// Copy existing wagons
for (int i = 0; i < oldLength; i++) {
newConsist[i] = oldOrders.consist.get(i);
}
// Then add specified wagon.
newConsist[oldLength] = wagonTypeNumber;
} else {
newConsist = new int[] { wagonTypeNumber };
}
newOrders = new TrainOrdersModel(oldOrders.getStationID(), new ImInts(
newConsist), oldOrders.getWaitUntilFull(), false);
s.setOrder(orderNumber, newOrders);
sendUpdateMove(s);
}

pathAsPoints

Class: jfreerails.controller.TrackPathFinder

Documentation

No documentation available

Source Code

public List<ImPoint> pathAsPoints() {
IntArray path = pathFinder.retrievePath();
return convertPath2Points(path);
}

processPreMove

Class: jfreerails.network.specifics.UntriedMoveReceiver

Documentation

No documentation available

Source Code

void processPreMove(PreMove pm);

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

/**
* Called when a new game is started or a game is loaded.
* <p>
* <b>Be extremely careful with the references of objects allocated in this
* method to avoid memory leaks - see bug 967677 (OutOfMemoryError after
* starting several new games). </b>
* </p>
*/

Source Code

/**
* Called when a new game is started or a game is loaded.
* <p>
* <b>Be extremely careful with the references of objects allocated in this
* method to avoid memory leaks - see bug 967677 (OutOfMemoryError after
* starting several new games). </b>
* </p>
*/
public void setup(RenderersRoot vl, ReadOnlyWorld w) throws IOException {
/*
* Set the cursor position. The initial cursor position is 0,0. However,
* if a game is loaded or a new game is started and the map size is the
* same as the last map size, then the cursor should take the position
* it had on the last map.
*/
ImPoint cursorPosition = new ImPoint(0, 0);
if (null != world) {
if (w.getMapWidth() == world.getMapWidth()
&& w.getMapHeight() == world.getMapHeight()) {
cursorPosition = (ImPoint) modelRoot
.getProperty(ModelRoot.Property.CURSOR_POSITION);
}
}
renderers = vl;
world = w;
modelRoot.addMapListener(this);
modelRoot.addListListener(this);
if (!vl.validate(world)) {
throw new IllegalArgumentException("The specified"
+ " RenderersRoot are not compatible with the clients"
+ "world!");
}
// create the main and overview maps
mainMap = new DetailMapRenderer(world, renderers, modelRoot);
TrainRenderer trainRenderer = mainMap.getTrainRenderer();
Dimension maxSize = new Dimension(200, 200);
overviewMap = ZoomedOutMapRenderer.getInstance(world, maxSize);
stationTypesPopup.setup(modelRoot, actionRoot, mainMap
.getStationRadius());
mapViewJComponent
.setup(mainMap, modelRoot, renderers);
// setup the the main and overview map JComponents
dialogueBoxController.setDefaultFocusOwner(mapViewJComponent);
userInputOnMapController.setup(mapViewJComponent, actionRoot
.getTrackMoveProducer(), stationTypesPopup, this.modelRoot,
dialogueBoxController, mapViewJComponent.getMapCursor(),
getBuildTrackController(), trainRenderer);
buildMenu.setup(actionRoot);
mainMapScrollPane1.setViewportView(this.mapViewJComponent);
((OverviewMapJComponent) overviewMapContainer).setup(overviewMap);
datejLabel.setup(modelRoot, vl, null);
cashjLabel.setup(modelRoot, vl, null);
trainsJTabPane.setup(actionRoot, vl, modelRoot);
dialogueBoxController.setup(modelRoot, vl);
StationPlacementCursor.wireUp(actionRoot, mainMap.getStationRadius(),
mapViewJComponent);
int gameSpeed = ((GameSpeed) world.get(ITEM.GAME_SPEED)).getSpeed();
/* Set the selected game speed radio button. */
String actionName = actionRoot.getServerControls().getGameSpeedDesc(
gameSpeed);
speedActions.setSelectedItem(actionName);
userMessageGenerator.logSpeed();
/*
* Count stations and trains to determine if we need to display the
* station and train menu items and tabs.3
*/
countStations();
countTrains();
String name = modelRoot.getPrincipal().getName();
String serverDetails = (String) modelRoot
.getProperty(ModelRoot.Property.SERVER);
String frameTitle;
if (serverDetails.equals(LocalConnection.SERVER_IN_SAME_JVM)) {
frameTitle = name + " - Freerails";
} else {
frameTitle = name + " - " + serverDetails + " - Freerails";
}
clientJFrame.setTitle(frameTitle);
isSetup = true;
modelRoot.setProperty(ModelRoot.Property.CURSOR_POSITION,
cursorPosition);
mapViewJComponent.requestFocus();
}

Called Methods

processingInstruction

Class: jfreerails.server.parser.Track_TilesParser

Documentation

No documentation available

Source Code

public void processingInstruction(java.lang.String target,
java.lang.String data) throws SAXException {
}

Called Methods

No outgoing method calls

getTrackPieceWhenOldTrackPieceIsNull

Class: jfreerails.move.ChangeTrackPieceCompositeMove

Documentation

No documentation available

Source Code

private static TrackPiece getTrackPieceWhenOldTrackPieceIsNull(
Step direction, TrackRule trackRule, int owner, int ruleNumber) {
TrackConfiguration simplestConfig = TrackConfiguration
.getFlatInstance("000010000");
TrackConfiguration trackConfiguration = TrackConfiguration.add(
simplestConfig, direction);
return new TrackPieceImpl(trackConfiguration, trackRule, owner,
ruleNumber);
}

TrainCrashException

Class: jfreerails.move.TrainCrashException

Documentation

No documentation available

Source Code

public TrainCrashException() {
}

Called Methods

No outgoing method calls

getTrackRule

Class: jfreerails.world.track.TrackPieceImpl

Documentation

No documentation available

Source Code

public TrackRule getTrackRule() {
return trackType;
}

Called Methods

No outgoing method calls

createDisplayMenu

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

public JMenu createDisplayMenu() {
displayMenu = new JMenu("Display");
displayMenu.setMnemonic(68);
trainOrdersJMenuItem = new JMenuItem("Train Orders");
trainOrdersJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showTrainOrders();
}
});
stationInfoJMenuItem = new JMenuItem("Station Info");
stationInfoJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showStationInfo(0);
}
});
trainListJMenuItem = new JMenuItem("Train List");
trainListJMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialogueBoxController.showTrainList();
}
});
displayMenu.add(trainOrdersJMenuItem);
displayMenu.add(stationInfoJMenuItem);
displayMenu.add(trainListJMenuItem);
displayMenu.addSeparator();
// Add menu items to control what gets displayed on the map.
final JCheckBoxMenuItem showCargoMenuItem = new JCheckBoxMenuItem(
"Show cargo at stations", true);
displayMenu.add(showCargoMenuItem);
showCargoMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modelRoot.setProperty(
ModelRoot.Property.SHOW_CARGO_AT_STATIONS, new Boolean(
showCargoMenuItem.isSelected()));
mapViewJComponent.refreshAll();
}
});
final JCheckBoxMenuItem showStationNamesMenuItem = new JCheckBoxMenuItem(
"Show station names", true);
displayMenu.add(showStationNamesMenuItem);
showStationNamesMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modelRoot.setProperty(ModelRoot.Property.SHOW_STATION_NAMES,
new Boolean(showStationNamesMenuItem.isSelected()));
mapViewJComponent.refreshAll();
}
});
final JCheckBoxMenuItem showStationBordersMenuItem = new JCheckBoxMenuItem(
"Show sphere-of-influence around stations", true);
displayMenu.add(showStationBordersMenuItem);
showStationBordersMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modelRoot.setProperty(ModelRoot.Property.SHOW_STATION_BORDERS,
new Boolean(showStationBordersMenuItem.isSelected()));
mapViewJComponent.refreshAll();
}
});
final JCheckBoxMenuItem playSoundsMenuItem = new JCheckBoxMenuItem(
"Play sounds", true);
displayMenu.add(playSoundsMenuItem);
playSoundsMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
modelRoot.setProperty(ModelRoot.Property.PLAY_SOUNDS,
new Boolean(playSoundsMenuItem.isSelected()));
}
});
;
boolean showFps = Boolean.parseBoolean(System.getProperty("SHOWFPS"));
final JCheckBoxMenuItem showFPSMenuItem = new JCheckBoxMenuItem(
"Show FPS stats", showFps);
displayMenu.add(showFPSMenuItem);
showFPSMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String newValue = String.valueOf(showFPSMenuItem.isSelected());
System.setProperty("SHOWFPS", newValue);
}
});
return displayMenu;
}

showCargoWaitingAndDemandActionPerformed

Class: experimental.DialogueBoxTester

Documentation

No documentation available

Source Code

private void showCargoWaitingAndDemandActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showCargoWaitingAndDemandActionPerformed
// Add your handling code here:
CargoWaitingAndDemandedJPanel panel = new CargoWaitingAndDemandedJPanel();
panel.setup(modelRoot, vl, closeCurrentDialogue);
int newStationID = 0;
panel.display(newStationID);
dialogueBoxController.showContent(panel);
}// GEN-LAST:event_showCargoWaitingAndDemandActionPerformed

getNewGameAction

Class: jfreerails.client.view.ServerControlModel

Documentation

/**
* When calling this action, set the action command string to the desired
* map name, or call the appropriate selectMapAction.
*
* @return an action to start a new game
*/

Source Code

/**
* When calling this action, set the action command string to the desired
* map name, or call the appropriate selectMapAction.
*
* @return an action to start a new game
*/
public Action getNewGameAction() {
return newGameAction;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.network.specifics.LogOnResponse

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof LogOnResponse))
return false;
final LogOnResponse logOnResponse = (LogOnResponse) o;
if (playerNumber != logOnResponse.playerNumber)
return false;
if (successful != logOnResponse.successful)
return false;
if (message != null ? !message.equals(logOnResponse.message)
: logOnResponse.message != null)
return false;
return true;
}

Called Methods

No outgoing method calls

getNewMapNames

Class: jfreerails.network.specifics.SavedGamesManager

Documentation

No documentation available

Source Code

String[] getNewMapNames();

Called Methods

No outgoing method calls

gotoIndex

Class: jfreerails.world.top.NonNullElements

Documentation

/** Moves the cursor to the specified index. */

Source Code

/** Moves the cursor to the specified index. */
public void gotoIndex(int i) {
int newRow = -1;
for (int j = 0; j < listSize(); j++) {
if (testCondition(j)) {
newRow++;
if (i == j) {
reset();
this.index = i;
this.row = newRow;
return;
}
}
}
throw new NoSuchElementException("Index:" + String.valueOf(i)
+ " Size:" + listSize() + " Row:" + newRow);
}

hashCode

Class: jfreerails.util.List3DImpl

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return sizeD1();
}

getPreferredSize

Class: jfreerails.client.view.MapViewJComponent

Documentation

No documentation available

Source Code

@Override
public Dimension getPreferredSize() {
return getMapSizeInPixels();
}

MoveChainFork

Class: jfreerails.network.specifics.MoveChainFork

Documentation

No documentation available

Source Code

public MoveChainFork() {
// do nothing
}

Called Methods

No outgoing method calls

loadProps

Class: jfreerails.launcher.Launcher

Documentation

No documentation available

Source Code

private void loadProps(){
try{
props = new Properties();
FileInputStream in = new FileInputStream("freerails.properties");
props.load(in);
in.close();
if(!props.containsKey("freerails.server.port") ||
!props.containsKey("freerails.server.port") ||
!props.containsKey("freerails.server.port")){
throw new Exception();
}
}catch (Exception e){
props = new Properties();
props.setProperty("freerails.server.port", "55000");
props.setProperty("freerails.player.name", System.getProperty("user.name"));
props.setProperty("freerails.server.ip.address", "127.0.0.1");
}
}

Called Methods

No outgoing method calls

stopGame

Class: jfreerails.controller.ServerControlInterface

Documentation

No documentation available

Source Code

void stopGame();

Called Methods

No outgoing method calls

getDefaultIcon

Class: jfreerails.client.renderer.TileRenderer

Documentation

No documentation available

Source Code

Image getDefaultIcon();

Called Methods

No outgoing method calls

hasNext

Class: jfreerails.controller.ToAndFroPathIterator

Documentation

No documentation available

Source Code

public boolean hasNext() {
if (list.size() < 2) {
return false;
}
return true;
}

Called Methods

No outgoing method calls

getOpposite

Class: jfreerails.world.common.PositionOnTrack

Documentation

/**
* @return the position on the track which is in the opposite direction.
*/

Source Code

/**
* @return the position on the track which is in the opposite direction.
*/
public PositionOnTrack getOpposite() {
int newX = this.getX() - this.cameFrom.deltaX;
int newY = this.getY() - this.cameFrom.deltaY;
Step newDirection = this.cameFrom.getOpposite();
return createComingFrom(newX, newY, newDirection);
}

testPickUpCargo1

Class: jfreerails.controller.DropOffAndPickupCargoMoveGeneratorTest

Documentation

/** Tests picking up cargo from a station. */

Source Code

/** Tests picking up cargo from a station. */
public void testPickUpCargo1() {
// Set up the variables for this test.
MutableCargoBundle cargoBundleWith2CarloadsOfCargo0 = new MutableCargoBundle();
// cargoBundleWith2CarloadsOfCargo0.setAmount(cargoType0FromStation2,
// 2);
cargoBundleWith2CarloadsOfCargo0.setAmount(cargoType0FromStation2, 80);
assertEquals("There shouldn't be any cargo at the station yet",
ImmutableCargoBundle.EMPTY_BUNDLE, getCargoAtStation());
assertEquals("There shouldn't be any cargo on the train yet",
ImmutableCargoBundle.EMPTY_BUNDLE, getCargoOnTrain());
// Now add 2 carloads of cargo type 0 to the station.
// getCargoAtStation().setAmount(cargoType0FromStation2, 2);
setCargoAtStation(cargoType0FromStation2, 80);
// The train should pick up this cargo, since it has three wagons
// capable of carrying cargo type 0.
stopAtStation();
// The train should now have the two car loads of cargo and there should
// be no cargo at the station.
assertEquals("There should no longer be any cargo at the station",
ImmutableCargoBundle.EMPTY_BUNDLE, getCargoAtStation());
assertEquals("The train should now have the two car loads of cargo",
cargoBundleWith2CarloadsOfCargo0.toImmutableCargoBundle(),
getCargoOnTrain());
}

waitForObject

Class: jfreerails.network.AbstractInetConnection

Documentation

No documentation available

Source Code

FreerailsSerializable waitForObject() throws InterruptedException,
IOException {
if (status.isOpen()) {
synchronized (inbound) {
if (inbound.size() > 0) {
return inbound.getFirst();
}
inbound.wait();
if (inbound.size() > 0) {
return inbound.getFirst();
}
throw new IllegalStateException();
}
}
throw new IOException("The connection is close.");
}

sizeD1

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

public int sizeD1() {
return super.size();
}

set

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

public void set(int d1, int d2, int d3, T element) {
super.set(element, d1, d2, d3);
}

loadTrainImages

Class: jfreerails.client.top.RenderersRootImpl

Documentation

No documentation available

Source Code

private void loadTrainImages(ReadOnlyWorld w, FreerailsProgressMonitor pm)
throws IOException {
// Setup progress monitor..
final int numberOfWagonTypes = w.size(SKEY.CARGO_TYPES);
final int numberOfEngineTypes = w.size(SKEY.ENGINE_TYPES);
pm.nextStep(numberOfWagonTypes + numberOfEngineTypes);
int progress = 0;
pm.setValue(progress);
//Load wagon images.
for (int i = 0; i < numberOfWagonTypes; i++) {
CargoType cargoType = (CargoType) w.get(SKEY.CARGO_TYPES, i);
String name = cargoType.getName();
TrainImages ti = new TrainImages(imageManager, name);
wagonImages.add(ti);
pm.setValue(++progress);
}
//Load engine images
for (int i = 0; i < numberOfEngineTypes; i++) {
EngineType engineType = (EngineType) w.get(SKEY.ENGINE_TYPES, i);
String engineTypeName = engineType
.getEngineTypeName();
TrainImages ti = new TrainImages(imageManager, engineTypeName);
engineImages.add(ti);
pm.setValue(++progress);
}
}

testTrackPieceLegality

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

public boolean testTrackPieceLegality(int trackTemplateToTest) {
TrackConfiguration trackConfiguration = TrackConfiguration
.from9bitTemplate(trackTemplateToTest);
return legalConfigurations
.trackConfigurationIsLegal(trackConfiguration);
}

setProperty

Class: jfreerails.launcher.LauncherInterface

Documentation

No documentation available

Source Code

void setProperty(String key, String value);

Called Methods

No outgoing method calls

getProperty

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public Object getProperty(Property p) {
return properties.get(p);
}

Called Methods

No outgoing method calls

BinaryNumberFormatterTest

Class: jfreerails.client.common.BinaryNumberFormatterTest

Documentation

No documentation available

Source Code

public BinaryNumberFormatterTest(String arg0) {
super(arg0);
}

Called Methods

No outgoing method calls

testIsFirstYear

Class: jfreerails.controller.StockPriceCalculatorTest

Documentation

No documentation available

Source Code

/*
* Test method for
* 'jfreerails.controller.StockPriceCalculator.isFirstYear(int)'
*/
public void testIsFirstYear() {
assertTrue(calc.isFirstYear(0));
GameCalendar calendar = (GameCalendar) w.get(ITEM.CALENDAR);
int tpy = calendar.getTicksPerYear();
int currentTicks = w.currentTime().getTicks();
GameTime newTime = new GameTime(currentTicks + tpy + 1);
w.setTime(newTime);
assertFalse(calc.isFirstYear(0));
newTime = new GameTime(currentTicks + tpy - 1);
w.setTime(newTime);
assertTrue(calc.isFirstYear(0));
}

setup

Class: jfreerails.client.view.LeaderBoardJPanel

Documentation

No documentation available

Source Code

public void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
ReadOnlyWorld w = modelRoot.getWorld();
values.clear();
this.submitButtonCallBack = closeAction;
for (int player = 0; player < w.getNumberOfPlayers(); player++) {
PlayerDetails details = new PlayerDetails();
FreerailsPrincipal principal = w.getPlayer(player).getPrincipal();
details.name = principal.getName();
NonNullElements stations = new NonNullElements(KEY.STATIONS, w,
principal);
details.stations = stations.size();
TransactionAggregator networth = new NetWorthCalculator(
w, principal);
details.networth = networth.calculateValue();
values.add(details);
}
Collections.sort(values);
playersList.setListData(values);
setSize(getPreferredSize());
}

testItem

Class: jfreerails.world.top.WorldDiffsTest

Documentation

No documentation available

Source Code

public void testItem() {
WorldImpl underlyingWorld = new WorldImpl(10, 10);
StationModel station0 = new StationModel();
StationModel station1 = new StationModel();
underlyingWorld.set(ITEM.GAME_RULES, station0); // why not!
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(station0, worldDiff.get(ITEM.GAME_RULES));
worldDiff.set(ITEM.GAME_RULES, station1);
assertEquals(station1, worldDiff.get(ITEM.GAME_RULES));
}

processMove

Class: jfreerails.client.top.UserMessageGenerator

Documentation

No documentation available

Source Code

public void processMove(Move move) {
if (move instanceof CompositeMove) {
ImList<Move> moves = ((CompositeMove) move).getMoves();
for (int i = 0; i < moves.size(); i++) {
processMove(moves.get(i));
}
}
if (move instanceof WorldDiffMove) {
WorldDiffMove wdm = (WorldDiffMove) move;
if (wdm.getCause().equals(WorldDiffMove.Cause.TrainArrives)) {
trainArrives(wdm);
}
} else if (move instanceof ChangeGameSpeedMove) {
logSpeed();
}
}

equals

Class: jfreerails.util.List3DImpl

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object obj) {
if (!(obj instanceof List3D))
return false;
return Lists.equals(this, (List3D)obj);
}

getActivity

Class: jfreerails.world.top.ActivityIteratorImpl

Documentation

No documentation available

Source Code

public Activity getActivity() {
return ant.act;
}

Called Methods

No outgoing method calls

tryDoMove

Class: jfreerails.move.Move

Documentation

/**
* Tests whether this Move can be executed on the specified world object,
* this method should leave the world object unchanged.
*/

Source Code

/**
* Tests whether this Move can be executed on the specified world object,
* this method should leave the world object unchanged.
*/
MoveStatus tryDoMove(World w, FreerailsPrincipal p);

Called Methods

No outgoing method calls

getPrerequisite

Class: jfreerails.world.terrain.Consumption

Documentation

No documentation available

Source Code

public int getPrerequisite() {
return prerequisite;
}

Called Methods

No outgoing method calls

formKeyPressed

Class: jfreerails.client.common.MyGlassPanel

Documentation

No documentation available

Source Code

// GEN-LAST:event_formMousePressed
private void formKeyPressed(java.awt.event.KeyEvent evt) { // GEN-FIRST:event_formKeyPressed
// Add your handling code here:
}

Called Methods

No outgoing method calls

moveTrains

Class: jfreerails.server.TrainUpdater

Documentation

No documentation available

Source Code

void moveTrains(ReadOnlyWorld world) {
int time = world.currentTime().getTicks();
for (int k = 0; k < world.getNumberOfPlayers(); k++) {
FreerailsPrincipal principal = world.getPlayer(k).getPrincipal();
//If a train is moving, we want it to keep moving rather than stop
//to allow an already stationary train to start moving. To achieve this
//we process moving trains first.
ArrayList<Integer> movingTrains = new ArrayList<Integer>();
ArrayList<Integer> stoppedTrains = new ArrayList<Integer>();
for (int i = 0; i < world.size(principal, KEY.TRAINS); i++) {
TrainModel train = (TrainModel) world.get(principal,
KEY.TRAINS, i);
if (null == train) {
continue;
}
TrainAccessor ta = new TrainAccessor(world, principal, i);
if (ta.isMoving(time)) {
movingTrains.add(i);
} else {
stoppedTrains.add(i);
}
}
for (int trainId : movingTrains) {
moveTrain(world, principal, trainId);
}
for (int trainId : stoppedTrains) {
moveTrain(world, principal, trainId);
}
}
}

TimeTickMove

Class: jfreerails.move.TimeTickMove

Documentation

No documentation available

Source Code

public TimeTickMove(GameTime oldTime, GameTime newTime) {
this.oldTime = oldTime;
this.newTime = newTime;
}

Called Methods

No outgoing method calls

test1

Class: jfreerails.controller.SharePriceCalculatorTest

Documentation

No documentation available

Source Code

public void test1() {
SharePriceCalculator cal = new SharePriceCalculator();
cal.networth = 100000;
cal.profitsLastYear = 100000;
cal.stockholderEquity = 500000;
cal.totalShares = 100000;
long expected = (100000 + 500000 + 100000 * 5) / 100000;
assertEquals(expected, cal.calculatePrice());
}

loadgame

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public void loadgame(String saveGameName) throws IOException {
logger.info("load game " + saveGameName);
newPlayersAllowed = false;
confirmedPlayers.clear();
ServerGameModel loadedGame;
loadedGame = (ServerGameModel) savedGamesManager.loadGame(saveGameName);
String[] passwords = loadedGame.getPasswords();
World w = loadedGame.getWorld();
assert passwords.length == w.getNumberOfPlayers();
ArrayList<NameAndPassword> newPlayers = new ArrayList<NameAndPassword>();
for (int i = 0; i < passwords.length; i++) {
Player player = w.getPlayer(i);
NameAndPassword nap = new NameAndPassword(player.getName(),
passwords[i]);
newPlayers.add(nap);
}
/*
* Remove any currently logged on players who are not participants in
* the game we are loading.
*/
for (NameAndPassword nap : players) {
if (!newPlayers.contains(nap) && currentlyLoggedOn.contains(nap)) {
removeConnection(nap);
}
}
players = newPlayers;
setServerGameModel(loadedGame);
sendWorldUpdatedCommand();
}

hasNext

Class: jfreerails.world.top.ActivityIteratorImpl

Documentation

No documentation available

Source Code

public boolean hasNext() {
return (activityIndex + 1) < size;
}

Called Methods

No outgoing method calls

characters

Class: jfreerails.server.parser.CargoAndTerrainParser

Documentation

/**
* This SAX interface method is implemented by the parser.
*
*/

Source Code

/**
* This SAX interface method is implemented by the parser.
*
*/
public final void characters(char[] chars, int start, int len)
throws SAXException {
buffer.append(chars, start, len);
}

Called Methods

No outgoing method calls

isTrainFull

Class: jfreerails.controller.TrainStopsHandler

Documentation

No documentation available

Source Code

public boolean isTrainFull() {
TrainAccessor train = new TrainAccessor(worldDiffs, principal, trainId);
ImInts spaceAvailable = train.spaceAvailable();
return spaceAvailable.sum() == 0;
}

contains

Class: jfreerails.world.common.Step

Documentation

No documentation available

Source Code

public boolean contains(FlatTrackTemplate ftt) {
if (ftt.get9bitTemplate() == this.flatTrackTemplate) {
return true;
}
return false;
}

readFromServer

Class: jfreerails.network.InetConnection2Server

Documentation

No documentation available

Source Code

public FreerailsSerializable[] readFromServer() throws IOException {
return read();
}

testHit2

Class: jfreerails.client.renderer.TrainRendererTest

Documentation

No documentation available

Source Code

@Test
public void testHit2() {
Point wagonCenter = new Point(100, 100);
Point mouseClick = new Point(90, 100);
boolean hit = isHit(wagonCenter, mouseClick, Step.NORTH);
assertFalse(hit);
}

getH

Class: jfreerails.controller.BuildTrackExplorer

Documentation

No documentation available

Source Code

public int getH() {
int xDistance = (target.x - currentPosition.getX())
* Step.TILE_DIAMETER;
int yDistance = (target.y - currentPosition.getY())
* Step.TILE_DIAMETER;
int sumOfSquares = (xDistance * xDistance + yDistance * yDistance);
return (int) Math.sqrt(sumOfSquares);
}

CityNamesRenderer

Class: jfreerails.client.renderer.CityNamesRenderer

Documentation

No documentation available

Source Code

public CityNamesRenderer(ReadOnlyWorld world) {
this.w = world;
}

Called Methods

No outgoing method calls

TrackTilesGenerator

Class: experimental.TrackTilesGenerator

Documentation

No documentation available

Source Code

public TrackTilesGenerator() {
Point2D.Double start, end, one, two;
track = new CubicCurve2D.Double[3];
track[0] = new CubicCurve2D.Double();
start = new Point2D.Double(150, 300);
end = new Point2D.Double(450, 150);
one = controlPoint(start);
two = controlPoint(end);
track[0].setCurve(start, one, two, end);
track[1] = TrackRenderer.createAdjacentCurve(track[0], 0, 0);
track[2] = TrackRenderer.createAdjacentCurve(track[0], -60, -60);
tr = new TrackRenderer();
URL track_xml_url = OldWorldImpl.class
.getResource("/jfreerails/data/track_tiles.xml");
Track_TilesHandlerImpl trackSetFactory = new Track_TilesHandlerImpl(
track_xml_url);
rules = trackSetFactory.getRuleList();
generateTiles();
}

getChangeAtStation

Class: jfreerails.move.TransferCargoAtStationMove

Documentation

No documentation available

Source Code

public ChangeCargoBundleMove getChangeAtStation() {
return (ChangeCargoBundleMove) super.getMoves().get(
CHANGE_AT_STATION_INDEX);
}

canAddToTail

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public boolean canAddToTail(TrainPositionOnMap b) {
return aHeadEqualsBTail(b, this);
}

start_Tiles

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* A container element start event handling method.
*
* @param meta
* attributes
*/

Source Code

/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_Tiles(final Attributes meta) throws SAXException;

Called Methods

No outgoing method calls

testUsingNullElements

Class: jfreerails.world.top.WorldDiffsTest

Documentation

No documentation available

Source Code

public void testUsingNullElements() {
WorldImpl underlyingWorld = new WorldImpl(10, 10);
underlyingWorld.addPlayer(player0);
StationModel station0 = new StationModel();
StationModel station1 = null;
underlyingWorld.add(player0.getPrincipal(), KEY.STATIONS, station0);
underlyingWorld.add(player0.getPrincipal(), KEY.STATIONS, station1);
WorldDiffs worldDiff = new WorldDiffs(underlyingWorld);
assertEquals(station0, worldDiff.get(player0
.getPrincipal(), KEY.STATIONS, 0));
assertEquals(station1, worldDiff.get(player0
.getPrincipal(), KEY.STATIONS, 1));
worldDiff.set(player0.getPrincipal(), KEY.STATIONS, 0, station1);
worldDiff.set(player0.getPrincipal(), KEY.STATIONS, 1, station0);
}

set

Class: jfreerails.util.List2DDiff

Documentation

No documentation available

Source Code

public void set(int d1, int d2, T element) {
super.set(element, d1, d2);
}

hashCode

Class: jfreerails.world.track.TrackSection

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((step == null) ? 0 : step.hashCode());
result = PRIME * result + ((tile == null) ? 0 : tile.hashCode());
return result;
}

SelectStationJPanel

Class: jfreerails.client.view.SelectStationJPanel

Documentation

No documentation available

Source Code

public SelectStationJPanel() {
initComponents();
}

generateFileNameNumber

Class: jfreerails.client.renderer.ChequeredTileRenderer

Documentation

No documentation available

Source Code

@Override
protected String generateFileNameNumber(int i) {
return String.valueOf(i);
}

Called Methods

No outgoing method calls

getOrder

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public TrainOrdersModel getOrder(int i) {
return orders.get(i);
}

Called Methods

No outgoing method calls

doPreMove

Class: jfreerails.client.common.ModelRootImpl

Documentation

No documentation available

Source Code

public MoveStatus doPreMove(PreMove pm) {
Move m = pm.generateMove(world);
MoveStatus ms = moveReceiver.tryDoMove(m);
moveReceiver.processPreMove(pm);
return ms;
}

deltaAssets

Class: jfreerails.world.accounts.Transaction

Documentation

No documentation available

Source Code

Money deltaAssets();

Called Methods

No outgoing method calls

cameFrom

Class: jfreerails.world.common.PositionOnTrack

Documentation

/**
* @return The direction the entity came from.
*/

Source Code

/**
* @return The direction the entity came from.
*/
public Step cameFrom() {
return cameFrom;
}

Called Methods

No outgoing method calls

setWorld

Class: jfreerails.server.ServerGameModelImpl

Documentation

No documentation available

Source Code

public void setWorld(World w, String[] passwords) {
this.world = w;
this.serverAutomata.clear();
this.passwords = passwords.clone();
}

Called Methods

  • _Dummy_.__Array__.clone (external)

listUpdated

Class: jfreerails.client.view.TrainDialogueJPanel

Documentation

No documentation available

Source Code

public void listUpdated(KEY key, int index, FreerailsPrincipal p) {
newTrainScheduleJPanel1.listUpdated(key, index, p);
}

assertBuildTrackFails

Class: jfreerails.move.ChangeTrackPieceCompositeMoveTest

Documentation

No documentation available

Source Code

private void assertBuildTrackFails(ImPoint p, Step v, TrackRule rule) {
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(p, v, rule, rule, getWorld(),
MapFixtureFactory.TEST_PRINCIPAL);
MoveStatus status = move.doMove(getWorld(), Player.AUTHORITATIVE);
assertEquals(false, status.isOk());
}

getOrder

Class: jfreerails.world.train.ImmutableSchedule

Documentation

No documentation available

Source Code

public TrainOrdersModel getOrder(int i) {
return orders.get(i);
}

removeLast

Class: jfreerails.world.common.ImInts

Documentation

No documentation available

Source Code

public ImInts removeLast() {
int[] newInts = new int[ints.length - 1];
System.arraycopy(ints, 0, newInts, 0, newInts.length);
return new ImInts(newInts);
}

Called Methods

No outgoing method calls

testBounds

Class: jfreerails.world.train.CompositeSpeedAgainstTimeTest

Documentation

No documentation available

Source Code

public void testBounds(){
SpeedAgainstTime sat = ConstAcc.uas(10, 2, 400d);
CompositeSpeedAgainstTime csat = new CompositeSpeedAgainstTime(sat);
double t = csat.duration();
double t2 = csat.calcT(400d);
assertEquals(t, t2);
double s = csat.calcS(t);
assertEquals(400d, s);
double t3 = csat.calcT(0d);
assertEquals(0d, t3);
}

end_ListOfTrackPieceTemplates

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* A container element end event handling method.
*/

Source Code

/**
* A container element end event handling method.
*/
void end_ListOfTrackPieceTemplates() throws SAXException;

Called Methods

No outgoing method calls

getStatus

Class: jfreerails.controller.IncrementalPathFinder

Documentation

No documentation available

Source Code

public abstract int getStatus();

Called Methods

No outgoing method calls

testPathOnTiles

Class: jfreerails.controller.AddTrainPreMoveTest

Documentation

/**
* Check that the path on tiles created for the new train is actually on
* the track.
*/

Source Code

/**
* Check that the path on tiles created for the new train is actually on
* the track.
*/
public void testPathOnTiles() {
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0),
stationA, principal, defaultSchedule);
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.ok);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
TrainMotion motion = ta.findCurrentMotion(0);
assertNotNull(motion);
PathOnTiles path = motion.getTiles(motion.duration());
assertTrackHere(path);
}

endElement

Class: jfreerails.server.parser.Track_TilesParser

Documentation

No documentation available

Source Code

public void endElement(java.lang.String ns, java.lang.String name,
java.lang.String qname) throws SAXException {
dispatch(false);
context.pop();
if ("CanOnlyBuildOnTheseTerrainTypes".equals(qname)) {
handler.end_CanOnlyBuildOnTheseTerrainTypes();
} else if ("ListOfTrackPieceTemplates".equals(qname)) {
handler.end_ListOfTrackPieceTemplates();
} else if ("ListOfLegalRoutesAcrossNode".equals(qname)) {
handler.end_ListOfLegalRoutesAcrossNode();
} else if ("CannotBuildOnTheseTerrainTypes".equals(qname)) {
handler.end_CannotBuildOnTheseTerrainTypes();
} else if ("TrackType".equals(qname)) {
handler.end_TrackType();
} else if ("Tiles".equals(qname)) {
handler.end_Tiles();
} else if ("TrackPieceTemplate".equals(qname)) {
handler.end_TrackPieceTemplate();
} else if ("TrackSet".equals(qname)) {
handler.end_TrackSet();
}
}

getS

Class: jfreerails.world.train.CompositeSpeedAgainstTime

Documentation

No documentation available

Source Code

public double getS() {
return finalS;
}

Called Methods

No outgoing method calls

getNumOrders

Class: jfreerails.world.train.MutableSchedule

Documentation

/**
* Returns number of non priority orders + number of priority orders.
*
* @return Number of orders.
*/

Source Code

/**
* Returns number of non priority orders + number of priority orders.
*
* @return Number of orders.
*/
public int getNumOrders() {
return orders.size();
}

Called Methods

No outgoing method calls

readResolve

Class: jfreerails.move.MoveStatus

Documentation

/**
* Avoid creating a duplicate when deserializing.
*/

Source Code

/**
* Avoid creating a duplicate when deserializing.
*/
private Object readResolve() {
if (ok) {
return MOVE_OK;
}
return this;
}

Called Methods

No outgoing method calls

genText

Class: jfreerails.controller.ReportBugTextGenerator

Documentation

No documentation available

Source Code

public static String genText(Exception e) {
StackTraceElement[] s = e.getStackTrace();
StringBuffer sb = new StringBuffer();
sb.append("Unexpected Exception\n");
sb.append("\n");
sb.append("Consider submitting a bug report using the sourceforge.net" +
" bug tracker at the following url:\n");
sb.append(TRACKER_URL);
sb.append("\n");
sb.append("\n");
sb.append("Please:\n");
sb.append(" 1. Use the following as the title of the bug report:\n\t");
sb.append(" Unexpected Exception: ");
sb.append(s[0].getFileName());
sb.append(" line ");
sb.append(s[0].getLineNumber());
sb.append("\n");
sb.append(" 2. Include steps to reproduce the bug (attach a save game if appropriate).\n");
sb.append(" 3. Copy and paste the details below into the bug report:\n");
appendBuildProps(sb);
sb.append("\n");
sb.append("\n\t");
sb.append(e.toString());
for (StackTraceElement ste : s) {
sb.append("\n\t\t at ");
sb.append(ste);
}
return sb.toString();
}

size

Class: jfreerails.world.common.ImList

Documentation

No documentation available

Source Code

public int size() {
return elementData.length;
}

Called Methods

No outgoing method calls

calTrackTotal

Class: jfreerails.controller.BalanceSheetGenerator

Documentation

No documentation available

Source Code

public static Money calTrackTotal(Transaction.Category category,
ReadOnlyWorld w, FreerailsPrincipal principal, GameTime startTime) {
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
w, principal);
aggregator.setCategory(TRACK);
long amount = 0;
for (int i = 0; i < w.size(SKEY.TRACK_RULES); i++) {
TrackRule trackRule = (TrackRule) w.get(SKEY.TRACK_RULES, i);
long trackValue = trackRule.getPrice().getAmount();
GameTime[] times = new GameTime[] { startTime,
GameTime.END_OF_THE_WORLD };
aggregator.setType(i);
aggregator.setTimes(times);
ItemsTransactionAggregator.QuantitiesAndValues qnv = aggregator
.calculateQuantitiesAndValues();
int quantity = qnv.quantities[0];
amount += trackValue * quantity
/ TrackConfiguration.LENGTH_OF_STRAIGHT_TRACK_PIECE;
}
return new Money(amount);
}

createTrainsJTabPane

Class: jfreerails.client.top.GUIComponentFactoryTestImpl

Documentation

No documentation available

Source Code

public JTabbedPane createTrainsJTabPane() {
return trainsJPanel;
}

Called Methods

No outgoing method calls

MoveTrainPreMove

Class: jfreerails.controller.MoveTrainPreMove

Documentation

No documentation available

Source Code

public MoveTrainPreMove(int id, FreerailsPrincipal p) {
trainID = id;
principal = p;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.move.AddPlayerMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof AddPlayerMove))
return false;
final AddPlayerMove addPlayerMove = (AddPlayerMove) o;
if (!player2add.equals(addPlayerMove.player2add))
return false;
return true;
}

PathWalkerImpl

Class: jfreerails.world.train.PathWalkerImpl

Documentation

No documentation available

Source Code

public PathWalkerImpl(FreerailsPathIterator i) {
it = i;
}

Called Methods

No outgoing method calls

getPort

Class: jfreerails.network.specifics.AbstractFreerailsServerTestCase

Documentation

No documentation available

Source Code

protected int getPort() {
return connectionAccepter.getLocalPort();
}

assertMapsAndSaveGamesReceived

Class: jfreerails.network.specifics.FreerailsClientTest

Documentation

No documentation available

Source Code

private void assertMapsAndSaveGamesReceived(FreerailsClient client)
throws IOException, InterruptedException {
// 2 commands to read.
Message2Client message2Client = (Message2Client) client.read();
message2Client.execute(client);
message2Client = (Message2Client) client.read();
message2Client.execute(client);
Object maps = client.getProperty(ClientProperty.MAPS_AVAILABLE);
assertNotNull(maps);
Object savedGames = client
.getProperty(ClientProperty.SAVED_GAMES);
assertNotNull(savedGames);
}

getUnderlyingSize

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

@Override
int getUnderlyingSize(int... dim) {
if(dim.length == 0)
return underlyingList.sizeD1();
if(dim.length == 1){
if (underlyingList.sizeD1() <= dim[0])
return -1;
return underlyingList.sizeD2(dim[0]);
}
if(dim.length == 2){
if (underlyingList.sizeD1() <= dim[0])
return -1;
if (underlyingList.sizeD2(dim[0]) <= dim[1])
return -1;
return underlyingList.sizeD3(dim[0], dim[1]);
}
throw new IllegalArgumentException(String.valueOf(dim.length));
}

getFrameCt

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public int getFrameCt() {
return frameCt;
}

Called Methods

No outgoing method calls

getOrderToGoto

Class: jfreerails.world.train.MutableSchedule

Documentation

/** Returns the number of the order the train is currently carry out. */

Source Code

/** Returns the number of the order the train is currently carry out. */
public int getOrderToGoto() {
return nextScheduledOrder;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.move.AddItemToListMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof AddItemToListMove) {
AddItemToListMove test = (AddItemToListMove) o;
if (null == this.item) {
if (null != test.item) {
return false;
}
} else if (!this.item.equals(test.getAfter())) {
return false;
}
if (this.index != test.index) {
return false;
}
if (this.listKey != test.listKey) {
return false;
}
return true;
}
return false;
}

getUnitWeight

Class: jfreerails.world.cargo.CargoType

Documentation

No documentation available

Source Code

public int getUnitWeight() {
return unitWeight;
}

Called Methods

No outgoing method calls

testHasNext

Class: jfreerails.world.train.PathWalkerImplTest

Documentation

No documentation available

Source Code

public void testHasNext() {
IntLine line = new IntLine();
setup();
assertTrue(!pw.hasNext());
pw.stepForward(10);
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertLineEquals(0, 0, 10, 0, line);
assertTrue(!pw.hasNext());
setup();
assertTrue(!pw.hasNext());
pw.stepForward(110);
assertTrue(pw.hasNext());
line = new IntLine();
pw.nextSegment(line);
assertLineEquals(0, 0, 100, 0, line);
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertLineEquals(100, 0, 100, 10, line);
assertTrue(!pw.hasNext());
/*
* Now test with underlying pathIterators with few elements.
*/
ArrayList<Point> points = new ArrayList<Point>();
assertHasNextEqualsFalse(points);
points = new ArrayList<Point>();
points.add(new Point(0, 0));
assertHasNextEqualsFalse(points);
points = new ArrayList<Point>();
points.add(new Point(0, 0));
points.add(new Point(100, 0));
FreerailsPathIterator it2 = FreerailsPathIteratorImpl
.forwardsIterator(points);
assertTrue(it2.hasNext());
pw = new PathWalkerImpl(it2);
assertTrue(!pw.hasNext());
pw.stepForward(1000);
assertTrue(pw.hasNext());
pw.nextSegment(line);
assertTrue(!pw.hasNext());
}

formatWithLowBitOnLeft

Class: jfreerails.client.common.BinaryNumberFormatter

Documentation

No documentation available

Source Code

public static String formatWithLowBitOnLeft(int i, int bits) {
StringBuffer buff = new StringBuffer(format(i, bits));
buff.reverse();
return buff.toString();
}

initComponents

Class: jfreerails.launcher.LauncherPanel1

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
buttonGroup1 = new javax.swing.ButtonGroup();
singlePlayerButton = new javax.swing.JRadioButton();
startNetworkButton = new javax.swing.JRadioButton();
joinNetworkButton = new javax.swing.JRadioButton();
serverOnlyButton = new javax.swing.JRadioButton();
paddingJPanel = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
setBorder(new javax.swing.border.TitledBorder(
new javax.swing.border.EtchedBorder(), "Select Game Type"));
buttonGroup1.add(singlePlayerButton);
singlePlayerButton.setSelected(true);
singlePlayerButton.setText("Single-Player");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(singlePlayerButton, gridBagConstraints);
buttonGroup1.add(startNetworkButton);
startNetworkButton.setText("Start a network game");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(startNetworkButton, gridBagConstraints);
buttonGroup1.add(joinNetworkButton);
joinNetworkButton.setText("Join a network game");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(joinNetworkButton, gridBagConstraints);
buttonGroup1.add(serverOnlyButton);
serverOnlyButton.setText("Server only");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(serverOnlyButton, gridBagConstraints);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 4;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(paddingJPanel, gridBagConstraints);
}// GEN-END:initComponents

Called Methods

No outgoing method calls

get8bitTemplate

Class: jfreerails.world.track.TrackConfiguration

Documentation

No documentation available

Source Code

public int get8bitTemplate() {
int newTemplate = 0;
Step[] vectors = Step.getList();
for (int i = 0; i < vectors.length; i++) {
if (this.contains(vectors[i])) {
newTemplate = newTemplate | vectors[i].get8bitTemplate();
}
}
return newTemplate;
}

LogOnResponse

Class: jfreerails.network.specifics.LogOnResponse

Documentation

No documentation available

Source Code

private LogOnResponse(boolean success, int i, String s) {
this.successful = success;
this.playerNumber = i;
this.message = s;
}

Called Methods

No outgoing method calls

setCenterTrain

Class: jfreerails.client.view.TrainListCellRenderer

Documentation

No documentation available

Source Code

public void setCenterTrain(boolean b) {
this.centerTrain = b;
}

Called Methods

No outgoing method calls

setDefaultFocusOwner

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void setDefaultFocusOwner(Component defaultFocusOwner) {
this.defaultFocusOwner = defaultFocusOwner;
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.world.train.EngineType

Documentation

No documentation available

Source Code

@Override
public String toString() {
return engineTypeName;
}

Called Methods

No outgoing method calls

addNoTunnelsButton

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

No documentation available

Source Code

private void addNoTunnelsButton() {
JToggleButton toggleButton = new JToggleButton();
tunnelButtonGroup.add(toggleButton);
toggleButton.setIcon(getIcon("no_tunnels"));
toggleButton.setPreferredSize(new java.awt.Dimension(36, 36));
toggleButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectionSet.put(TrackRule.TrackCategories.tunnel, null);
setBuildTrackStrategy();
}
});
toggleButton.setToolTipText("Don't build tunnels");
tunnelsJPanel.add(toggleButton);
}

getID

Class: jfreerails.network.specifics.LoadGameMessage2Server

Documentation

No documentation available

Source Code

public int getID() {
return id;
}

Called Methods

No outgoing method calls

showSelectSavedGame2Load

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showSelectSavedGame2Load(){
Message2Server refreshGames = new RefreshListOfGamesMessage2Server(2);
modelRoot.sendCommand(refreshGames);
LoadGameJPanel loadGameJPane = new LoadGameJPanel();
loadGameJPane.setup(modelRoot, vl, this.closeCurrentDialogue);
showContent(loadGameJPane);
}

update

Class: jfreerails.server.TrainMaintenanceMoveGenerator

Documentation

No documentation available

Source Code

public void update(World w) {
for (int i = 0; i < w.getNumberOfPlayers(); i++) {
FreerailsPrincipal principal = w.getPlayer(i).getPrincipal();
Move m = generateMove(w, principal);
moveReceiver.processMove(m);
}
}

testCanBuiltStationHere

Class: jfreerails.controller.StationBuilderTest

Documentation

No documentation available

Source Code

public void testCanBuiltStationHere() {
}

Called Methods

No outgoing method calls

World2ListModelAdapter

Class: jfreerails.client.view.World2ListModelAdapter

Documentation

No documentation available

Source Code

public World2ListModelAdapter(ReadOnlyWorld world, KEY key,
FreerailsPrincipal p) {
this.w = world;
if (null == key)
throw new NullPointerException();
if (null == p)
throw new NullPointerException();
if (null == w)
throw new NullPointerException();
// Check that the principal exists.
if (!world.isPlayer(p))
throw new IllegalArgumentException(p.getName());
elements = new NonNullElements(key, world, p);
}

limitPlayerNames

Class: jfreerails.launcher.ClientOptionsJPanel

Documentation

/**
* If the user has opted to load a game, we need to limit the list of
* players to participants in the game we are loading. Otherwise, any player
* name is OK. Either, pass in a array of names or null if any name is OK.
*/

Source Code

/**
* If the user has opted to load a game, we need to limit the list of
* players to participants in the game we are loading. Otherwise, any player
* name is OK. Either, pass in a array of names or null if any name is OK.
*/
void limitPlayerNames(String[] n) {
this.names = n;
if (names == null) {
playerName.setVisible(true);
playerNames.setVisible(false);
playerName.setEditable(true);
} else {
if (names.length == 1) {
playerName.setVisible(true);
playerNames.setVisible(false);
playerName.setText(n[0]);
playerName.setEditable(false);
} else {
playerName.setVisible(false);
playerNames.setVisible(true);
ComboBoxModel model = new DefaultComboBoxModel(names);
playerNames.setModel(model);
}
}
this.revalidate();
}

Called Methods

No outgoing method calls

canBuiltStationHere

Class: jfreerails.client.top.StationTypesPopup

Documentation

No documentation available

Source Code

public boolean canBuiltStationHere(Point p) {
stationBuildModel.getStationBuildAction().putValue(
StationBuildModel.StationBuildAction.STATION_POSITION_KEY, p);
FreerailsTile tile = (FreerailsTile) modelRoot.getWorld().getTile(p.x,
p.y);
return tile.hasTrack();
}

tryDoMove

Class: jfreerails.network.specifics.UntriedMoveReceiver

Documentation

No documentation available

Source Code

MoveStatus tryDoMove(Move move);

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.common.GameTime

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof GameTime) {
GameTime test = (GameTime) o;
return this.ticks == test.ticks;
}
return false;
}

Called Methods

No outgoing method calls

undoMove

Class: jfreerails.move.ChangeTileMove

Documentation

No documentation available

Source Code

public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.isOk()) {
w.setTile(x, y, before);
}
return ms;
}

LegalTrackPlacement

Class: jfreerails.world.track.LegalTrackPlacement

Documentation

No documentation available

Source Code

public LegalTrackPlacement(HashSet<TerrainType.Category> types,
PlacementRule placementRule) {
this.placementRule = placementRule;
Iterator<TerrainType.Category> iterator = types.iterator();
HashSet<TerrainType.Category> temp = new HashSet<TerrainType.Category>();
while (iterator.hasNext()) {
temp.add(iterator.next());
}
terrainTypes = new ImHashSet<TerrainType.Category>(temp);
}

Called Methods

No outgoing method calls

setup

Class: jfreerails.world.train.PathWalkerImplTest

Documentation

No documentation available

Source Code

public void setup() {
int[] xpoints = { 0, 100, 100 };
int[] ypoints = { 0, 0, 100 };
it = new SimplePathIteratorImpl(xpoints, ypoints);
pw = new PathWalkerImpl(it);
}

Called Methods

No outgoing method calls

testGetTiles

Class: jfreerails.controller.MoveTrainPreMove1stTest

Documentation

No documentation available

Source Code

public void testGetTiles() {
setupLoopOfTrack();
MoveTrainPreMove moveTrain = new MoveTrainPreMove(0, principal);
Move m = moveTrain.generateMove(world);
assertTrue(m.doMove(world, principal).ok);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
TrainMotion motion = ta.findCurrentMotion(1);
double duration = motion.duration();
assertTrue(duration > 1);
int trainLength = motion.getTrainLength();
for (int i = 0; i < 10; i++) {
double t = i == 0 ? 0 : duration * i / 10;
PathOnTiles tiles = motion.getTiles(t);
assertTrue("t=" + t, tiles.steps() > 0);
assertTrue("t=" + t, tiles.getTotalDistance() >= trainLength);
}
}

getMapHeight

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

/**
* Returns the height of the map in tiles.
*/

Source Code

/**
* Returns the height of the map in tiles.
*/
int getMapHeight();

Called Methods

No outgoing method calls

processCargo

Class: jfreerails.controller.ProcessCargoAtStationMoveGenerator

Documentation

No documentation available

Source Code

public static ArrayList<Move> processCargo(ReadOnlyWorld w,
CargoBundle bundle, int stationID, FreerailsPrincipal p,
int trainId) {
StationModel thisStation = (StationModel) w.get(p,
KEY.STATIONS, stationID);
Iterator<CargoBatch> batches = bundle.cargoBatchIterator();
ArrayList<Move> moves = new ArrayList<Move>();
while (batches.hasNext()) {
CargoBatch batch = batches.next();
double distanceSquared = (batch.getSourceX() - thisStation.x)
* (batch.getSourceX() - thisStation.x)
+ (batch.getSourceY() - thisStation.y)
* (batch.getSourceY() - thisStation.y);
double dist = Math.sqrt(distanceSquared);
int quantity = bundle.getAmount(batch);
double amount = quantity * Math.log(dist) * MAGIC_NUMBER;
Money money = new Money((long) amount);
DeliverCargoReceipt receipt = new DeliverCargoReceipt(money,
quantity, stationID, batch, trainId);
moves.add(new AddTransactionMove(p, receipt));
}
return moves;
}

validateInput

Class: jfreerails.launcher.LauncherPanel

Documentation

No documentation available

Source Code

boolean validateInput();

Called Methods

No outgoing method calls

showTerrainInfoActionPerformed

Class: experimental.DialogueBoxTester

Documentation

No documentation available

Source Code

private void showTerrainInfoActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_showTerrainInfoActionPerformed
// Add your handling code here:
int terrainType = 0;
dialogueBoxController.showTerrainInfo(terrainType);
}// GEN-LAST:event_showTerrainInfoActionPerformed

getTrackConfiguration

Class: jfreerails.world.track.TrackPieceImpl

Documentation

No documentation available

Source Code

public TrackConfiguration getTrackConfiguration() {
return configuration;
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.world.cargo.MutableCargoBundle

Documentation

No documentation available

Source Code

@Override
public String toString() {
return toImmutableCargoBundle().toString();
}

getCargoType

Class: jfreerails.world.terrain.Consumption

Documentation

No documentation available

Source Code

public int getCargoType() {
return cargoType;
}

Called Methods

No outgoing method calls

countOpenConnections

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public synchronized int countOpenConnections() {
Iterator<NameAndPassword> it = acceptedConnections.keySet().iterator();
int numConnections = 0;
while (it.hasNext()) {
Connection2Client connection = acceptedConnections.get(it.next());
if (connection.isOpen()) {
numConnections++;
}
}
return numConnections;
}

getCargoType

Class: jfreerails.world.terrain.Production

Documentation

No documentation available

Source Code

public int getCargoType() {
return cargoType;
}

Called Methods

No outgoing method calls

removeCompleteMoveReceiver

Class: jfreerails.network.specifics.MoveChainFork

Documentation

No documentation available

Source Code

public void removeCompleteMoveReceiver(MoveReceiver moveReceiver) {
if (null == moveReceiver) {
throw new NullPointerException();
}
moveReceivers.remove(moveReceiver);
}

Called Methods

No outgoing method calls

nextButtonActionPerformed

Class: jfreerails.launcher.Launcher

Documentation

No documentation available

Source Code

private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_nextButtonActionPerformed
try {
CardLayout cl = (CardLayout) jPanel1.getLayout();
LauncherPanel1 panel = (LauncherPanel1) wizardPages[0];
SelectMapJPanel msp = (SelectMapJPanel) wizardPages[1];
ClientOptionsJPanel cop = (ClientOptionsJPanel) wizardPages[2];
hideAllMessages();
switch (currentPage) {
case 0:
msp.validateInput();
/* Initial game selection page */
switch (panel.getMode()) {
case LauncherPanel1.MODE_SERVER_ONLY:
/* go to map selection screen */
cl.next(jPanel1);
msp.setServerPortPanelVisible(true);
currentPage++;
break;
case LauncherPanel1.MODE_SINGLE_PLAYER:
/* go to map selection screen */
cl.next(jPanel1);
msp.setServerPortPanelVisible(false);
cop.setRemoteServerPanelVisible(false);
currentPage++;
break;
case LauncherPanel1.MODE_START_NETWORK_GAME:
/* go to map selection screen */
msp.setServerPortPanelVisible(true);
cop.setRemoteServerPanelVisible(false);
cl.next(jPanel1);
currentPage++;
break;
case LauncherPanel1.MODE_JOIN_NETWORK_GAME:
/* client display options */
nextIsStart = true;
cl.show(jPanel1, "2");
currentPage = 2;
msp.setServerPortPanelVisible(false);
cop.setRemoteServerPanelVisible(true);
cop.limitPlayerNames(null);
break;
}
prevButton.setEnabled(true);
break;
case 1:
/* map selection page */
if (panel.getMode() == LauncherPanel1.MODE_SERVER_ONLY) {
if (msp.validateInput()) {
prevButton.setEnabled(false);
try {
if (!isNewGame()) {
initServer();
server
.loadgame(ServerControlInterface.FREERAILS_SAV);
}
prepare2HostNetworkGame(msp.getServerPort());
} catch (BindException be) {
// When the port is already in use.
prevButton.setEnabled(true);
setInfoText(be.getMessage(),
LauncherInterface.WARNING);
}
}
} else {
if (isNewGame()) {
cop.limitPlayerNames(null);
} else {
initServer();
server.loadgame(msp.getSaveGameName());
String[] playernames = server.getPlayerNames();
cop.limitPlayerNames(playernames);
}
nextIsStart = true;
prevButton.setEnabled(true);
setNextEnabled(true);
currentPage++;
cl.next(jPanel1);
}
break;
case 2:
/* display mode selection */
if (panel.getMode() == LauncherPanel1.MODE_START_NETWORK_GAME) {
if (msp.validateInput()) {
prevButton.setEnabled(false);
int mode = cop.getScreenMode();
prepare2HostNetworkGame(msp.getServerPort());
client = new GUIClient(cop.getPlayerName(),
progressPanel, mode, cop.getDisplayMode());
client.connect(server, cop.getPlayerName(), "password");
}
} else {
prevButton.setEnabled(false);
cop.setControlsEnabled(false);
startGame();
}
break;
case 3:
try {
/* Connection status screen */
prevButton.setEnabled(false);
setServerGameModel();// TODO catch exception
if (panel.getMode() == LauncherPanel1.MODE_START_NETWORK_GAME) {
startThread(server, client);
cl.show(jPanel1, "4");
} else {
/* Start a stand alone server. */
startThread(server);
setVisible(false);
}
setButtonsVisible(false);
setNextEnabled(false);
} catch (IOException e) {
setInfoText(e.getMessage(), LauncherInterface.WARNING);
cop.setControlsEnabled(true);
prevButton.setEnabled(true);
setNextEnabled(true);
currentPage = 1;
cl.show(jPanel1, "1");
return;
}
break;
default:
throw new IllegalArgumentException(String.valueOf(currentPage));
}
} catch (Exception e) {
exit(e);
}
}// GEN-LAST:event_nextButtonActionPerformed

setHtml

Class: jfreerails.client.view.HtmlJPanel

Documentation

No documentation available

Source Code

void setHtml(String s) {
htmlJLabel.setText(s);
}

Called Methods

No outgoing method calls

getUnderlyingSize

Class: jfreerails.util.List1DDiff

Documentation

No documentation available

Source Code

@Override
int getUnderlyingSize(int... dim) {
if (dim.length != 0)
throw new IllegalArgumentException(String.valueOf(dim.length));
return underlyingList.size();
}

getT

Class: jfreerails.world.accounts.TransactionAndTimeStamp

Documentation

No documentation available

Source Code

public Transaction getT() {
return t;
}

Called Methods

No outgoing method calls

compareTo

Class: jfreerails.util.ListKey

Documentation

No documentation available

Source Code

public int compareTo(ListKey o) {
if(o.listID != listID)
return o.listID.ordinal() - listID.ordinal();
if(index.length != o.index.length)
return index.length -o.index.length;
for (int i = 0; i < index.length; i++) {
if(index[i] != o.index[i])
return index[i] -o.index[i];
}
if(o.type != type)
return o.type.ordinal() - type.ordinal();
return 0;
}

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.top.BuildMenu

Documentation

No documentation available

Source Code

public void setup(ActionRoot actionRoot) {
this.removeAll();
this.setText("Build");
add(actionRoot.getBuildTrainDialogAction());
}

getFirstVectorToTry

Class: jfreerails.controller.FlatTrackExplorer

Documentation

No documentation available

Source Code

Step getFirstVectorToTry() {
if (beforeFirst) {
// Return the vector that is 45 degrees clockwise from the opposite
// of the current position.
Step v = this.currentPosition.cameFrom();
v = v.getOpposite();
int i = v.getID();
i++;
i = i % 8;
v = Step.getInstance(i);
return v;
}
// Return the vector that is 45 degrees clockwise from the direction
// of the current branch.
Step v = this.currentBranch.cameFrom();
int i = v.getID();
i++;
i = i % 8;
v = Step.getInstance(i);
return v;
}

setUp

Class: jfreerails.util.List1DDiffsTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
list = new List1DImpl<Object>();
map = new TreeMap<ListKey, Object>();
diffs = new List1DDiff<Object>(map, list, test.test);
}

Called Methods

No outgoing method calls

actionPerformed

Class: jfreerails.client.view.StationBuildAction

Documentation

No documentation available

Source Code

public void actionPerformed(ActionEvent e) {
Point value = (Point) stationBuildAction
.getValue(StationBuildAction.STATION_POSITION_KEY);
MoveStatus ms = stationBuilder.buildStation(new ImPoint(value.x,
value.y));
String message = null;
if (ms.isOk()) {
stationBuildAction.setEnabled(false);
} else {
message = ms.message;
}
modelRoot.setProperty(ModelRoot.Property.CURSOR_MESSAGE, message);
}

testAddD2

Class: jfreerails.util.List3DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List3DDiff.addD2(int)'
*/
public void testAddD2() {
underlying.addD1();
underlying.addD1();
diffs.addD2(0);
assertEquals(1, diffs.sizeD2(0));
diffs.addD2(0);
assertEquals(2, diffs.sizeD2(0));
diffs.addD2(1);
assertEquals(1, diffs.sizeD2(1));
}

getStationCancelAction

Class: jfreerails.client.view.StationBuildModel

Documentation

No documentation available

Source Code

public Action getStationCancelAction() {
return stationCancelAction;
}

Called Methods

No outgoing method calls

TrainUpdater

Class: jfreerails.server.TrainUpdater

Documentation

No documentation available

Source Code

public TrainUpdater(MoveReceiver mr) {
moveReceiver = mr;
if (null == mr) {
throw new NullPointerException();
}
}

Called Methods

No outgoing method calls

sendListOfConnectedPlayers2Clients

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

private void sendListOfConnectedPlayers2Clients() throws IOException {
/* Send the client the list of players. */
String[] playerNames = getPlayerNames();
Message2Client request = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.CONNECTED_CLIENTS, new ImStringList(
playerNames));
send2All(request);
}

testEquals

Class: jfreerails.world.cargo.CargoBundleTest

Documentation

No documentation available

Source Code

public void testEquals() {
MutableCargoBundle bundle1 = new MutableCargoBundle();
MutableCargoBundle bundle2 = new MutableCargoBundle();
CargoBatch batch1 = new CargoBatch(1, 2, 3, 4, 5);
CargoBatch batch2 = new CargoBatch(4, 2, 3, 4, 5);
int q1 = 10;
int q2 = 20;
bundle1.addCargo(batch1, q1);
bundle1.addCargo(batch2, q2);
assertBundlesNotEqual(bundle1, bundle2);
bundle2.addCargo(batch2, q2);
assertBundlesNotEqual(bundle1, bundle2);
bundle2.addCargo(batch1, q1);
assertBundlesEqual(bundle1, bundle2);
}

makeTrainWait

Class: jfreerails.controller.TrainStopsHandler

Documentation

No documentation available

Source Code

void makeTrainWait(int ticks) {
GameTime currentTime = worldDiffs.currentTime();
timeLoadingFinished = new GameTime(currentTime.getTicks() + ticks);
}

getBuildCost

Class: jfreerails.world.terrain.TerrainType

Documentation

No documentation available

Source Code

Money getBuildCost();

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.network.specifics.NameAndPassword

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result = 17;
result = result * 37 + password.hashCode();
result = result * 37 + username.hashCode();
return result;
}

Called Methods

No outgoing method calls

fireRefresh

Class: jfreerails.client.view.TrainOrdersListModel

Documentation

No documentation available

Source Code

public void fireRefresh() {
super.fireContentsChanged(this, 0, getSize());
}

initComponents

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
trainOrderJPanel1 = new jfreerails.client.view.TrainOrderJPanel();
editOrderJPopupMenu = new javax.swing.JPopupMenu();
gotoStationJMenuItem = new javax.swing.JMenuItem();
changeStation = new javax.swing.JMenuItem();
removeStationJMenuItem = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JSeparator();
addWagonJMenu = new javax.swing.JMenu();
removeWagonsJMenu = new javax.swing.JMenu();
removeLastJMenuItem = new javax.swing.JMenuItem();
removeAllJMenuItem = new javax.swing.JMenuItem();
changeConsistJMenu = new javax.swing.JMenu();
noChangeJMenuItem = new javax.swing.JMenuItem();
engineOnlyJMenuItem = new javax.swing.JMenuItem();
autoConsistJMenuItem = new javax.swing.JMenuItem();
waitJMenu = new javax.swing.JMenu();
dontWaitJMenuItem = new javax.swing.JMenuItem();
waitUntilFullJMenuItem = new javax.swing.JMenuItem();
jSeparator2 = new javax.swing.JSeparator();
pullUpJMenuItem = new javax.swing.JMenuItem();
pushDownJMenuItem = new javax.swing.JMenuItem();
selectStationJPanel1 = new jfreerails.client.view.SelectStationJPanel();
selectStationJPopupMenu = new javax.swing.JPopupMenu();
this.selectStationJPopupMenu.add(selectStationJPanel1);
addStationJButton = new javax.swing.JButton();
priorityOrdersJButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
orders = new javax.swing.JList();
gotoStationJMenuItem.setText("Goto station");
gotoStationJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
gotoStationJMenuItemActionPerformed(evt);
}
});
editOrderJPopupMenu.add(gotoStationJMenuItem);
changeStation.setText("Change Station");
changeStation.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
changeStationActionPerformed(evt);
}
});
editOrderJPopupMenu.add(changeStation);
removeStationJMenuItem.setText("Remove station");
removeStationJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeStationJMenuItemActionPerformed(evt);
}
});
editOrderJPopupMenu.add(removeStationJMenuItem);
editOrderJPopupMenu.add(jSeparator1);
addWagonJMenu.setText("Add Wagon");
editOrderJPopupMenu.add(addWagonJMenu);
removeWagonsJMenu.setText("Remove wagon(s)");
removeLastJMenuItem.setText("Remove last");
removeLastJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeLastJMenuItemActionPerformed(evt);
}
});
removeWagonsJMenu.add(removeLastJMenuItem);
removeAllJMenuItem.setText("Remove all wagons");
removeAllJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
removeAllJMenuItemActionPerformed(evt);
}
});
removeWagonsJMenu.add(removeAllJMenuItem);
editOrderJPopupMenu.add(removeWagonsJMenu);
changeConsistJMenu.setText("Change consist to..");
noChangeJMenuItem.setText("'No change'");
noChangeJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
noChangeJMenuItemActionPerformed(evt);
}
});
changeConsistJMenu.add(noChangeJMenuItem);
engineOnlyJMenuItem.setText("Engine only");
engineOnlyJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
engineOnlyJMenuItemActionPerformed(evt);
}
});
changeConsistJMenu.add(engineOnlyJMenuItem);
autoConsistJMenuItem.setText("Choose wagons automatically");
autoConsistJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
autoConsistJMenuItemActionPerformed(evt);
}
});
changeConsistJMenu.add(autoConsistJMenuItem);
editOrderJPopupMenu.add(changeConsistJMenu);
waitJMenu.setText("Wait at station");
dontWaitJMenuItem.setText("Don't wait");
dontWaitJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dontWaitJMenuItemActionPerformed(evt);
}
});
waitJMenu.add(dontWaitJMenuItem);
waitUntilFullJMenuItem.setText("Wait until full");
waitUntilFullJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
waitUntilFullJMenuItemActionPerformed(evt);
}
});
waitJMenu.add(waitUntilFullJMenuItem);
editOrderJPopupMenu.add(waitJMenu);
editOrderJPopupMenu.add(jSeparator2);
pullUpJMenuItem.setText("Pull up");
pullUpJMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pullUpJMenuItemActionPerformed(evt);
}
});
editOrderJPopupMenu.add(pullUpJMenuItem);
pushDownJMenuItem.setText("Push down");
pushDownJMenuItem
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pushDownJMenuItemActionPerformed(evt);
}
});
editOrderJPopupMenu.add(pushDownJMenuItem);
setLayout(new java.awt.GridBagLayout());
setBorder(new javax.swing.border.TitledBorder("Schedule"));
addStationJButton.setText("Add Station");
addStationJButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addStationJButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(addStationJButton, gridBagConstraints);
priorityOrdersJButton.setText("Add Priority Orders");
priorityOrdersJButton
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
priorityOrdersJButtonActionPerformed(evt);
}
});
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.insets = new java.awt.Insets(7, 7, 7, 7);
add(priorityOrdersJButton, gridBagConstraints);
jScrollPane1.setPreferredSize(new java.awt.Dimension(280, 160));
orders
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
orders.setCellRenderer(trainOrderJPanel1);
orders.addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
ordersKeyPressed(evt);
}
});
orders.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
ordersMouseClicked(evt);
}
});
jScrollPane1.setViewportView(orders);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(3, 3, 3, 3);
add(jScrollPane1, gridBagConstraints);
}// GEN-END:initComponents

test4

Class: jfreerails.network.specifics.MovePrecommitterTest

Documentation

/** Test test rejection 2. */

Source Code

/** Test test rejection 2. */
public void test4() {
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
assertFalse(oldtime.equals(newTime));
/* the following move should fail! */
Move m = new TimeTickMove(newTime, oldtime);
MoveStatus ms = m.tryDoMove(w, Player.AUTHORITATIVE);
assertFalse(ms.ok);
committer.toServer(m);
assertTrue(committer.blocked);
assertEquals(1, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
committer.fromServer(ms);
assertFalse(committer.blocked);
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
}

refreshAll

Class: jfreerails.client.renderer.ZoomedOutMapRenderer

Documentation

No documentation available

Source Code

public void refreshAll() {
refresh();
}

testGetYear

Class: jfreerails.world.common.GameCalenderTest

Documentation

No documentation available

Source Code

public void testGetYear() {
GameCalendar gc = new GameCalendar(10, 1900);
assertEquals("1900", gc.getYearAsString(0));
assertEquals("1900", gc.getYearAsString(5));
assertEquals("1901", gc.getYearAsString(10));
assertEquals("1950", gc.getYearAsString(505));
}

buildTrain

Class: jfreerails.server.MapCustomizer

Documentation

No documentation available

Source Code

public MapCustomizer buildTrain(ImPoint a, int... stops) {
FreerailsPrincipal principal = w.getPlayer(0).getPrincipal();
MutableSchedule s = new MutableSchedule();
for (int stop : stops) {
s.addOrder(new TrainOrdersModel(stop, null, false, true));
}
ImmutableSchedule defaultSchedule = s.toImmutableSchedule();
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(),
a, principal, defaultSchedule);
Move m = preMove.generateMove(w);
MoveStatus status = m.doMove(w, Player.AUTHORITATIVE);
if (!status.ok) {
throw new IllegalStateException(status.message);
}
return this;
}

testRemoveLastD1

Class: jfreerails.util.List3DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List3DDiff.removeLastD1()'
*/
public void testRemoveLastD1() {
underlying.addD1();
underlying.addD1();
assertEquals(2, diffs.sizeD1());
diffs.removeLastD1();
assertEquals(1, diffs.sizeD1());
diffs.removeLastD1();
assertEquals(0, diffs.sizeD1());
try{
diffs.removeLastD1();
fail();
}catch (Exception e) {
}
}

readResolve

Class: jfreerails.world.top.KEY

Documentation

No documentation available

Source Code

private Object readResolve() throws ObjectStreamException {
return keys[this.keyNumber];
}

Called Methods

No outgoing method calls

read

Class: jfreerails.util.CompressedInputStream

Documentation

No documentation available

Source Code

@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}

getTrackPiece

Class: jfreerails.world.track.FreerailsTile

Documentation

No documentation available

Source Code

public TrackPiece getTrackPiece() {
return trackPiece;
}

Called Methods

No outgoing method calls

TrainAccessor

Class: jfreerails.controller.TrainAccessor

Documentation

No documentation available

Source Code

public TrainAccessor(final ReadOnlyWorld w, final FreerailsPrincipal p,
final int id) {
this.w = w;
this.p = p;
this.id = id;
}

Called Methods

No outgoing method calls

setTotalsArrayLength

Class: jfreerails.controller.FinancialDataGatherer

Documentation

No documentation available

Source Code

@Override
protected void setTotalsArrayLength(int length) {
// TODO Auto-generated method stub
super.setTotalsArrayLength(length);
}

get

Class: jfreerails.util.List3DImpl

Documentation

No documentation available

Source Code

public List<T> get(int d1, int d2) {
return elementData.get(d1).get(d2);
}

Called Methods

No outgoing method calls

goFullScreen

Class: jfreerails.controller.ScreenHandler

Documentation

No documentation available

Source Code

private static void goFullScreen(JFrame frame, DisplayMode displayMode) {
setRepaintOffAndDisableDoubleBuffering(frame);
/*
* We need to make the frame not displayable before calling
* setUndecorated(true) otherwise a
* java.awt.IllegalComponentStateException will get thrown.
*/
if (frame.isDisplayable()) {
frame.dispose();
}
frame.setUndecorated(true);
device.setFullScreenWindow(frame);
if (device.isDisplayChangeSupported()) {
if (null == displayMode) {
displayMode = getBestDisplayMode();
}
logger.info("Setting display mode to: "
+ (new MyDisplayMode(displayMode).toString()));
device.setDisplayMode(displayMode);
}
frame.validate();
}

buildArray

Class: jfreerails.util.ArrayBase

Documentation

/**
* Constructs and returns a simple array containing the same data as held in
* a portion of this growable array. This override of the base class method
* checks that the portion specified actually has data present before
* constructing the returned array.
*
* @param type
* element type for constructed array
* @param offset
* start offset in array
* @param length
* number of characters to use
* @return array containing a copy of the data
*/

Source Code

/**
* Constructs and returns a simple array containing the same data as held in
* a portion of this growable array. This override of the base class method
* checks that the portion specified actually has data present before
* constructing the returned array.
*
* @param type
* element type for constructed array
* @param offset
* start offset in array
* @param length
* number of characters to use
* @return array containing a copy of the data
*/
@Override
protected Object buildArray(Class type, int offset, int length) {
if (offset + length <= countPresent) {
return super.buildArray(type, offset, length);
}
throw new ArrayIndexOutOfBoundsException();
}

undoMove

Class: jfreerails.move.AddTransactionMove

Documentation

No documentation available

Source Code

public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.ok) {
w.removeLastTransaction(this.principal);
}
return ms;
}

ChangeProductionAtEngineShopMove

Class: jfreerails.move.ChangeProductionAtEngineShopMove

Documentation

No documentation available

Source Code

public ChangeProductionAtEngineShopMove(ImList<PlannedTrain> b,
ImList<PlannedTrain> a, int station, FreerailsPrincipal p) {
this.before = b;
this.after = a;
this.stationNumber = station;
this.principal = p;
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.world.top.TestActivity

Documentation

No documentation available

Source Code

@Override
public String toString() {
return getClass().getName() + "{" + duration + "}";
}

Called Methods

No outgoing method calls

setProperty

Class: jfreerails.controller.ModelRoot

Documentation

No documentation available

Source Code

void setProperty(Property property, Object newValue);

Called Methods

No outgoing method calls

isCrashSite

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public boolean isCrashSite() {
return crashSite;
}

Called Methods

No outgoing method calls

getKey

Class: jfreerails.move.AddItemToListMove

Documentation

No documentation available

Source Code

public KEY getKey() {
return listKey;
}

Called Methods

No outgoing method calls

get

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

/**
* Returns the element at the specified position in the specified list.
*/

Source Code

/**
* Returns the element at the specified position in the specified list.
*/
FreerailsSerializable get(FreerailsPrincipal p, KEY key, int index);

Called Methods

No outgoing method calls

paintTrain

Class: jfreerails.client.renderer.TrainRenderer

Documentation

No documentation available

Source Code

public void paintTrain(Graphics g, TrainModel train, TrainPositionOnMap s, TrainImages.Highlight highlight) {
// If the train has been removed, it will be null!
if (train == null) {
return;
}
/*
* XXX HACK !! really our position ought to be defined at all times, but
* this is a workaround until we can fix movement
*/
if (s == null) {
return;
}
List<Entry<Point, Step>> positions = calcPositions(train, s);
if(null != highlight){
paintTrainHighlight(g, train, positions, highlight);
}
paintTrain(g, train, positions);
}

paintTile

Class: jfreerails.client.renderer.MapLayerRenderer

Documentation

No documentation available

Source Code

void paintTile(Graphics g, int tileX, int tileY);

Called Methods

No outgoing method calls

getVertexConnectedByEdge

Class: jfreerails.controller.FlatTrackExplorer

Documentation

No documentation available

Source Code

public int getVertexConnectedByEdge() {
return currentBranch.toInt();
}

paintTile

Class: jfreerails.client.renderer.TrackLayer

Documentation

No documentation available

Source Code

public void paintTile(Graphics g, int tileX, int tileY) {
/*
* Since track tiles overlap the adjacent terrain tiles, we create a
* temporary Graphics object that only lets us draw on the selected
* tile.
*/
paintRectangleOfTiles(g, new Rectangle(tileX, tileY, 1, 1));
}

Called Methods

  • jfreerails.client.renderer.MapBackgroundRender.TrackLayer.paintRectangleOfTiles (external)

readFromServer

Class: jfreerails.network.LocalConnection

Documentation

No documentation available

Source Code

public FreerailsSerializable[] readFromServer() throws IOException {
if (status.isOpen()) {
return fromServer.read();
}
throw new IOException();
}

ChangeItemInListMove

Class: jfreerails.move.ChangeItemInListMove

Documentation

No documentation available

Source Code

public ChangeItemInListMove(KEY k, int index, FreerailsSerializable before,
FreerailsSerializable after, FreerailsPrincipal p) {
this.before = before;
this.after = after;
this.index = index;
this.listKey = k;
this.principal = p;
}

Called Methods

No outgoing method calls

setUp

Class: jfreerails.controller.FinancialDataGathererTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
player =new Player("Player X", 0);
w = new WorldImpl();
Move addPlayer = AddPlayerMove.generateMove(w, player);
MoveStatus ms = addPlayer.doMove(w, Player.AUTHORITATIVE);
assertTrue(ms.ok);
}

RHSJTabPane

Class: jfreerails.client.view.RHSJTabPane

Documentation

No documentation available

Source Code

public RHSJTabPane() {
/*
* Dont accept keyboard focus since we want to leave it with the main
* map view.
*/
setFocusable(false);
ImageIcon trainListIcon;
ImageIcon buildTrackIcon;
/* set up trainsJTabbedPane */
setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
terrainInfoPanel = new TerrainInfoJPanel();
trainListPanel = new TrainListJPanel(true);
buildTrackPanel = new BuildTrackJPanel();
trainListPanel.removeButtons();
URL terrainInfoIconUrl = getClass().getResource(
"/jfreerails/client/graphics/icons/terrain_info.png");
ImageIcon terrainInfoIcon = new ImageIcon(terrainInfoIconUrl);
URL buildTrackIconUrl = getClass().getResource(
"/jfreerails/client/graphics/icons/track_new.png");
buildTrackIcon = new ImageIcon(buildTrackIconUrl);
URL trainListIconUrl = getClass().getResource(
"/jfreerails/client/graphics/icons/train_list.png");
trainListIcon = new ImageIcon(trainListIconUrl);
// Note titles set to null so only the icon appears at the top of the
// top.
JScrollPane terrainInfoJScrollPane = new JScrollPane(terrainInfoPanel);
terrainInfoJScrollPane
.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
addTab(null, terrainInfoIcon, terrainInfoJScrollPane, "Terrain Info");
stationInfoPanel = new StationInfoJPanel();
stationInfoPanel.removeCloseButton();
// Don't show the station info tab until it has been rewritten to take
// up less space.
// JScrollPane stationInfoJScrollPane = new
// JScrollPane(stationInfoPanel);
// stationInfoJScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
// addTab(null, stationInfoIcon, stationInfoJScrollPane, "Station
// Info");
// this.stationInfoIndex= this.getTabCount()-1;
trainListPanel.setTrainViewHeight(20);
addTab(null, buildTrackIcon, buildTrackPanel, "Build Track");
addTab(null, trainListIcon, trainListPanel, "Train List");
this.trainListIndex = this.getTabCount() - 1;
/* These values were picked by trial and error! */
this.setMinimumSize(new Dimension(250, 200));
}

Launcher

Class: jfreerails.launcher.Launcher

Documentation

No documentation available

Source Code

public Launcher(boolean quickstart) {
loadProps();
initComponents();
wizardPages[0] = new LauncherPanel1(this);
wizardPages[1] = new SelectMapJPanel(this);
wizardPages[2] = new ClientOptionsJPanel(this);
wizardPages[3] = new ConnectedPlayersJPanel();
if (!quickstart) {
jPanel1.add(wizardPages[0], "0");
jPanel1.add(wizardPages[1], "1");
jPanel1.add(wizardPages[2], "2");
jPanel1.add(wizardPages[3], "3");
jPanel1.add(progressPanel, "4");
pack();
} else {
prevButton.setVisible(false);
nextButton.setVisible(false);
pack();
}
hideAllMessages();
}

tryDoMove

Class: jfreerails.move.TimeTickMove

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
if (w.currentTime().equals(oldTime)) {
return MoveStatus.MOVE_OK;
}
String string = "oldTime = " + oldTime.getTicks() + " <=> "
+ "currentTime " + (w.currentTime()).getTicks();
return MoveStatus.moveFailed(string);
}

testMovingRoundLoop

Class: jfreerails.controller.MoveTrainPreMove1stTest

Documentation

No documentation available

Source Code

public void testMovingRoundLoop() {
setupLoopOfTrack();
MoveTrainPreMove moveTrain = new MoveTrainPreMove(0, principal);
Move m = moveTrain.generateMove(world);
assertTrue(m.doMove(world, principal).ok);
}

Node

Class: jfreerails.controller.Node

Documentation

No documentation available

Source Code

Node(int[] e, int[] d) {
if (e.length != d.length) {
throw new IllegalArgumentException("e.length=" + e.length
+ ", e.length=" + e.length);
}
edges = e;
distances = d;
}

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.view.IncomeStatementHtmlJPanel

Documentation

No documentation available

Source Code

@Override
public void setup(ModelRoot modelRoot, RenderersRoot vl,
Action closeAction) {
super.setup(modelRoot, vl, closeAction);
this.modelRoot = modelRoot;
updateHtml();
}

checkContract

Class: jfreerails.world.train.ConstAccTest

Documentation

/** Checks the specified object satisfies the contract defined by
* the interface SpeedAgainstTime.
*/

Source Code

/** Checks the specified object satisfies the contract defined by
* the interface SpeedAgainstTime.
*/
public static void checkContract(SpeedAgainstTime sat){
double s = sat.getS();
double ulps = Math.ulp(s);
double t = sat.getT();
double ulpt = Math.ulp(t);
//Check calcS()
checkCalcSCalcVandCalcA(sat, 0 - Double.MIN_VALUE);
checkCalcSCalcVandCalcA(sat, t + ulpt);
checkCalcSCalcVandCalcA(sat, 0 + Double.MIN_VALUE);
checkCalcSCalcVandCalcA(sat, t - ulpt);
for(double d = 0; d < 1d; d += 0.1d){
checkCalcSCalcVandCalcA(sat, t * d);
}
double actualS = sat.calcS(0);
assertEquals(0d, actualS);
actualS = sat.calcS(t);
assertEquals(s, actualS);
//Check calcT()
checkCalcT(sat, 0 - Double.MIN_VALUE);
checkCalcT(sat, s + ulps);
checkCalcT(sat, 0 + Double.MIN_VALUE);
checkCalcT(sat, s - ulps);
for(double d = 0; d < 1d; d += 0.1d){
checkCalcT(sat, s * d);
}
double actualT = sat.calcT(0);
assertEquals(0d, actualT);
actualT = sat.calcT(s);
assertEquals(t, actualT);
}

getNumberOfPlayers

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public int getNumberOfPlayers() {
return players.size();
}

testSettingNullElement

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

public void testSettingNullElement(){
underlying.addD1();
underlying.addD2(0, null);
underlying.addD2(0, new Integer(1));
assertEquals(null, diffs.get(0,0));
diffs.set(0, 0, new Integer(0));
assertEquals(new Integer(0), diffs.get(0,0));
assertEquals(new Integer(1), diffs.get(0,1));
diffs.set(0, 1, null);
assertEquals(null, diffs.get(0,1));
}

endElement

Class: jfreerails.server.parser.CargoAndTerrainParser

Documentation

/**
* This SAX interface method is implemented by the parser.
*
*/

Source Code

/**
* This SAX interface method is implemented by the parser.
*
*/
public final void endElement(java.lang.String ns, java.lang.String name,
java.lang.String qname) throws SAXException {
dispatch(false);
context.pop();
if ("Tile".equals(name)) {
handler.end_Tile();
} else if ("Cargo_Types".equals(name)) {
handler.end_Cargo_Types();
} else if ("Terrain_Types".equals(name)) {
handler.end_Terrain_Types();
} else if ("Types".equals(name)) {
handler.end_Types();
}
}

actionPerformed

Class: jfreerails.client.view.Unknown

Documentation

No documentation available

Source Code

public void actionPerformed(ActionEvent arg0) {
Move bondTransaction = new AddTransactionMove(modelRoot
.getPrincipal(), BondTransaction.repayBond(5));
modelRoot.doMove(bondTransaction);
}

testAddAndRemove2

Class: jfreerails.util.List1DDiffsTest

Documentation

No documentation available

Source Code

public void testAddAndRemove2(){
list.add(String.valueOf(1));
list.add(String.valueOf(1));
list.add(String.valueOf(1));
diffs.removeLast();
diffs.removeLast();
assertEquals(1, diffs.size());
assertEquals(1, map.size());
diffs.add(String.valueOf(2));
diffs.add(String.valueOf(2));
diffs.add(String.valueOf(2));
diffs.add(String.valueOf(2));
assertEquals(5, diffs.size());
assertEquals("4 elements + end=5", 5, map.size());
assertEquals(String.valueOf(1), diffs.get(0));
assertEquals(String.valueOf(2), diffs.get(1));
assertEquals(String.valueOf(2), diffs.get(2));
assertEquals(String.valueOf(2), diffs.get(3));
assertEquals(String.valueOf(2), diffs.get(3));
diffs.set(String.valueOf(3), 2);
assertEquals(5, diffs.size());
assertEquals(5, map.size());
assertEquals(String.valueOf(3), diffs.get(2));
diffs.set(String.valueOf(4), 4);
assertEquals(String.valueOf(4), diffs.get(4));
diffs.removeLast();
diffs.removeLast();
diffs.removeLast();
diffs.removeLast();
assertEquals(1, diffs.size());
assertEquals("fork=1", 1, map.size());
}

getTypeName

Class: jfreerails.world.track.TrackRuleImpl

Documentation

No documentation available

Source Code

public String getTypeName() {
return properties.getTypeName();
}

toString

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("TrainPosition {");
for (int i = 0; i < xpoints.size(); i++) {
sb.append("(");
sb.append(xpoints.get(i));
sb.append(", ");
sb.append(ypoints.get(i));
sb.append("), ");
}
sb.append("}");
return sb.toString();
}

getMapSizeInPixels

Class: jfreerails.client.renderer.ZoomedOutMapRenderer

Documentation

No documentation available

Source Code

/*
* @see NewMapView#getMapSizeInPixels()
*/
public Dimension getMapSizeInPixels() {
return new Dimension(imageWidth, imageHeight);
}

Called Methods

No outgoing method calls

setCancelButtonActionListener

Class: jfreerails.client.view.SelectEngineJPanel

Documentation

/**
* Removes any existing ActionListener listeners from the cancel button,
* then adds the specified one.
*/

Source Code

/**
* Removes any existing ActionListener listeners from the cancel button,
* then adds the specified one.
*/
void setCancelButtonActionListener(ActionListener l) {
ActionListener[] oldListeners = canceljButton.getActionListeners();
for (int i = 0; i < oldListeners.length; i++) {
canceljButton.removeActionListener(oldListeners[i]);
}
this.canceljButton.addActionListener(l);
}

Called Methods

No outgoing method calls

undoMove

Class: jfreerails.move.ChangeItemInListMove

Documentation

No documentation available

Source Code

public MoveStatus undoMove(World w, FreerailsPrincipal p) {
return move(before, after, w);
}

TrackMoveProducer

Class: jfreerails.controller.TrackMoveProducer

Documentation

No documentation available

Source Code

public TrackMoveProducer(MoveExecutor executor, ReadOnlyWorld world, ModelRoot mr) {
if(null == mr) throw new NullPointerException();
this.executor = executor;
this.mr = mr;
FreerailsPrincipal principal = executor.getPrincipal();
transactionsGenerator = new TrackMoveTransactionsGenerator(world,
principal);
setBuildTrackStrategy(BuildTrackStrategy.getDefault(world));
}

deltaCash

Class: jfreerails.world.accounts.Transaction

Documentation

/** Positive means credit. */

Source Code

/** Positive means credit. */
Money deltaCash();

Called Methods

No outgoing method calls

itemRemoved

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

public void itemRemoved(KEY key, int index, FreerailsPrincipal p) {
// do nothing.
}

Called Methods

No outgoing method calls

propertyChange

Class: jfreerails.client.view.TrainListJPanel

Documentation

No documentation available

Source Code

@Override
public void propertyChange(ModelRoot.Property p, Object oldValue, Object newValue) {
if(ModelRoot.Property.SELECTED_TRAIN == p){
if(!newValue.equals(this.getSelectedTrainID())){
//update needed..
TrainModel train = (TrainModel) world.get(principal, KEY.TRAINS, (int) newValue);
this.jList1.setSelectedValue(train, true);
}
}
}

getTrackPiece

Class: jfreerails.world.track.NullTrackType

Documentation

No documentation available

Source Code

public TrackPiece getTrackPiece(TrackConfiguration config, int owner) {
throw new UnsupportedOperationException("Method not implemented yet!");
}

Called Methods

No outgoing method calls

setGameModel

Class: jfreerails.network.specifics.FreerailsClient

Documentation

No documentation available

Source Code

public final void setGameModel(FreerailsMutableSerializable o) {
world = (World) o;
committer = new MovePrecommitter(world);
newWorld(world);
}

sizeD2

Class: jfreerails.util.List2D

Documentation

No documentation available

Source Code

int sizeD2(int d1);

Called Methods

No outgoing method calls

itemAdded

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

public void itemAdded(KEY key, int index, FreerailsPrincipal p) {
// do nothing.
}

Called Methods

No outgoing method calls

setupMap

Class: jfreerails.server.MapFactory

Documentation

No documentation available

Source Code

public static void setupMap(URL map_url, WorldImpl w,
FreerailsProgressMonitor pm) {
// Setup progress monitor..
pm.setValue(0);
world = w;
Image mapImage = (new ImageIcon(map_url)).getImage();
Rectangle mapRect = new java.awt.Rectangle(0, 0, mapImage
.getWidth(null), mapImage.getHeight(null));
BufferedImage mapBufferedImage = new BufferedImage(mapRect.width,
mapRect.height, BufferedImage.TYPE_INT_ARGB);
Graphics g = mapBufferedImage.getGraphics();
g.drawImage(mapImage, 0, 0, null);
w.setupMap(mapRect.width, mapRect.height);
pm.nextStep(mapRect.width);
HashMap<Integer, Integer> rgb2TerrainType = new HashMap<Integer, Integer>();
for (int i = 0; i < w.size(SKEY.TERRAIN_TYPES); i++) {
TerrainType tilemodel = (TerrainType) w.get(SKEY.TERRAIN_TYPES, i);
rgb2TerrainType.put(tilemodel.getRGB(), i);
}
TerrainType terrainTypeTile;
for (int c = 0; c < w.size(SKEY.TERRAIN_TYPES); c++) {
terrainTypeTile = (TerrainType) w.get(SKEY.TERRAIN_TYPES, c);
if (terrainTypeTile.getCategory().equals(
TerrainType.Category.Country)) {
if ((!terrainTypeTile.getTerrainTypeName().equals("Clear"))) {
countryTypes.add(new Integer(c));
}
}
if (terrainTypeTile.getCategory()
.equals(TerrainType.Category.Ocean)
|| terrainTypeTile.getCategory().equals(
TerrainType.Category.River)
|| terrainTypeTile.getCategory().equals(
TerrainType.Category.Hill)) {
non_countryTypes.add(new Integer(c));
}
}
TerrainRandomiser terrainRandomiser = new TerrainRandomiser(
countryTypes, non_countryTypes);
/*
* create vector to keep track of terrain randomisation 'clumping'
*/
Vector<RandomTerrainValue> locations = new Vector<RandomTerrainValue>();
for (int x = 0; x < mapRect.width; x++) {
pm.setValue(x);
for (int y = 0; y < mapRect.height; y++) {
int rgb = mapBufferedImage.getRGB(x, y);
FreerailsTile tile;
Integer type = rgb2TerrainType.get(rgb);
if (null == type) {
throw new NullPointerException(
"There is no terrain type mapped to rgb value "
+ rgb + " at location " + x + ", " + y);
}
tile = FreerailsTile.getInstance(terrainRandomiser
.getNewType(type.intValue()));
if (countryTypes.contains(tile.getTerrainTypeID())) {
locations.add(new RandomTerrainValue(x, y, tile
.getTerrainTypeID()));
}
w.setTile(x, y, tile);
}
}
for (int i = 0; i < locations.size(); i++) {
RandomTerrainValue rtv = locations.elementAt(i);
FreerailsTile tile = FreerailsTile.getInstance(rtv.getType());
int x = rtv.getX();
int y = rtv.getY();
int val = 3;
double prob = 0.75;
if (w.boundsContain(x - val, y - val)
&& w.boundsContain(x + val, y + val)) {
for (int m = x - val; m < x + val; m++) {
for (int n = y - val; n < y + val; n++) {
if (Math.random() > prob) {
setTile(m, n, tile);
}
}
}
}
}
}

getRowID

Class: jfreerails.world.top.WorldIterator

Documentation

/**
* Returns the number of the row where the cursor is (the first row is 0).
*/

Source Code

/**
* Returns the number of the row where the cursor is (the first row is 0).
*/
int getRowID();

Called Methods

No outgoing method calls

calculateValue

Class: jfreerails.world.top.TransactionAggregator

Documentation

/** Returns the sum of the appropriate transactions. Do not override. */

Source Code

/** Returns the sum of the appropriate transactions. Do not override. */
final public Money calculateValue() {
Money[] values = calculateValues();
return values[0];
}

getUnderlyingList

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

@Override
Object getUnderlyingList() {
return underlyingList;
}

Called Methods

No outgoing method calls

PathOnTrackFinder

Class: jfreerails.controller.PathOnTrackFinder

Documentation

No documentation available

Source Code

public PathOnTrackFinder(ReadOnlyWorld world) {
this.world = world;
}

Called Methods

No outgoing method calls

run

Class: jfreerails.util.FlowRateOutputStream

Documentation

No documentation available

Source Code

public void run() {
if (running) {
throw new Error("Starting thread task on an already-started object");
}
if (measureInterval == 0x7fffffffffffffffL) {
return;
}
running = true;
try {
do {
try {
Thread.currentThread();
Thread.sleep(measureInterval);
} catch (InterruptedException interruptedexception) {
}
if (!closeRequested) {
long totalByteSentCopy = totalByteSent;
long byteSentThisTime = totalByteSentCopy
- previousTotalByteSent;
previousTotalByteSent = totalByteSentCopy;
byteSentCumul -= byteSent[nextFree];
byteSent[nextFree] = byteSentThisTime;
byteSentCumul += byteSentThisTime;
nextFree = (nextFree + 1) % byteSent.length;
nbUsed = Math.min(byteSent.length, nbUsed + 1);
if (showTrace) {
logger
.info(String
.valueOf(String
.valueOf((new StringBuffer(
"Stream "))
.append(streamName)
.append(
": Open duration = ")
.append(
(System
.currentTimeMillis() - openTimeMillis) / 1000D)
.append(
", Byte sent = ")
.append(totalByteSent)
.append(" (")
.append(
(int) (totalByteSent / 1024D))
.append(
" Ko), current flow rate = ")
.append(
currentRateString())
.append(" Ko/s"))));
}
}
} while (!closeRequested);
// } catch (IOException ioexception) {
} finally {
running = false;
}
}

deltaAssets

Class: jfreerails.world.accounts.AddItemTransaction

Documentation

No documentation available

Source Code

public Money deltaAssets() {
return amount.changeSign();
}

testGetTimeOfDay

Class: jfreerails.world.common.GameCalenderTest

Documentation

No documentation available

Source Code

public void testGetTimeOfDay() {
GameCalendar gc = new GameCalendar(24, 1900);
assertEquals("00:00", gc.getTimeOfDay(0));
assertEquals("01:00", gc.getTimeOfDay(1));
assertEquals("15:00", gc.getTimeOfDay(15));
gc = new GameCalendar(24 * 60, 1900);
assertEquals("00:00", gc.getTimeOfDay(0));
assertEquals("00:10", gc.getTimeOfDay(10));
assertEquals("05:10", gc.getTimeOfDay(310));
}

equals

Class: jfreerails.move.AddTransactionMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object obj) {
if (obj instanceof AddTransactionMove) {
AddTransactionMove test = (AddTransactionMove) obj;
return test.principal.equals(this.principal)
&& test.transaction.equals(this.transaction);
}
return false;
}

Called Methods

No outgoing method calls

getRGB

Class: jfreerails.world.terrain.NullTerrainType

Documentation

No documentation available

Source Code

public int getRGB() {
return 0;
}

Called Methods

No outgoing method calls

pushDown

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public void pushDown(int orderNumber) {
if (!canPushDown(orderNumber)) {
throw new IllegalArgumentException(String.valueOf(orderNumber));
}
boolean isGoingToThisStation = getOrderToGoto() == orderNumber;
TrainOrdersModel order = getOrder(orderNumber);
removeOrder(orderNumber);
addOrder(orderNumber + 1, order);
if (isGoingToThisStation) {
setOrderToGoto(orderNumber + 1);
}
}

addMainmapzoomMenuItem

Class: experimental.SimpleComponentFactoryImpl2

Documentation

No documentation available

Source Code

private void addMainmapzoomMenuItem(JMenu displayMenu, final float scale) {
String menuItemName = "Set main map scale=" + scale;
JMenuItem menuItem = new JMenuItem(menuItemName);
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Rectangle visRect = mainMap.getVisibleRect();
int oldWidth = mainMap.getWidth();
mainMap.setup(new BlankMapRenderer(scale));
int newWidth = mainMap.getPreferredSize().width;
int oldCenterX = visRect.x + (visRect.width / 2);
int newCenterX = oldCenterX * newWidth / oldWidth;
visRect.x = newCenterX - visRect.width / 2;
int oldCenterY = visRect.y + (visRect.height / 2);
int newCenterY = oldCenterY * newWidth / oldWidth;
visRect.y = newCenterY - visRect.height / 2;
/*
* LL: I'm not sure why the 'if' is necessary in the following,
* but the view does not center on the right spot without it.
*/
if (oldWidth < newWidth) {
mainMap.setSize(mainMap.getPreferredSize());
mainMap.scrollRectToVisible(visRect);
} else {
mainMap.scrollRectToVisible(visRect);
mainMap.setSize(mainMap.getPreferredSize());
}
}
});
displayMenu.add(menuItem);
}

canAddToHead

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public boolean canAddToHead(TrainPositionOnMap b) {
return aHeadEqualsBTail(this, b);
}

doMove

Class: jfreerails.move.ChangeTileMove

Documentation

No documentation available

Source Code

public MoveStatus doMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryDoMove(w, p);
if (ms.isOk()) {
w.setTile(x, y, after);
}
return ms;
}

getDialogueBoxController

Class: jfreerails.client.view.ActionRoot

Documentation

No documentation available

Source Code

public DialogueBoxController getDialogueBoxController() {
return dialogueBoxController;
}

Called Methods

No outgoing method calls

setCategory

Class: jfreerails.world.top.ItemsTransactionAggregator

Documentation

No documentation available

Source Code

public void setCategory(Transaction.Category category) {
this.category = category;
}

Called Methods

No outgoing method calls

spaceAvailable

Class: jfreerails.controller.TrainAccessor

Documentation

/** The space available on the train measured in cargo units.*/

Source Code

/** The space available on the train measured in cargo units.*/
public ImInts spaceAvailable(){
TrainModel train = (TrainModel) w.get(p, KEY.TRAINS, id);
ImmutableCargoBundle bundleOnTrain = (ImmutableCargoBundle) w.get(p,
KEY.CARGO_BUNDLES, train.getCargoBundleID());
return spaceAvailable2(w, bundleOnTrain, train.getConsist());
}

getDefaultIcon

Class: jfreerails.client.top.SimpleTileRenderer

Documentation

No documentation available

Source Code

public Image getDefaultIcon() {
return i;
}

Called Methods

No outgoing method calls

hypotenuse

Class: jfreerails.util.Utils

Documentation

No documentation available

Source Code

public static int hypotenuse(int a, int b) {
double d = Math.hypot(a, b);
return (int) Math.round(d);
}

Called Methods

No outgoing method calls

size

Class: jfreerails.network.SynchronizedQueue

Documentation

No documentation available

Source Code

public synchronized int size() {
return queue.size();
}

Called Methods

No outgoing method calls

undoMove

Class: jfreerails.move.ChangeTrackPieceMove

Documentation

No documentation available

Source Code

public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus moveStatus = tryUndoMove(w, p);
if (!moveStatus.isOk()) {
return moveStatus;
}
move(w, this.trackPieceAfter, this.trackPieceBefore);
return moveStatus;
}

setDialogueBoxController

Class: jfreerails.client.view.ActionRoot

Documentation

No documentation available

Source Code

public void setDialogueBoxController(
DialogueBoxController dialogueBoxController) {
this.dialogueBoxController = dialogueBoxController;
}

Called Methods

No outgoing method calls

getOldTrackPiece

Class: jfreerails.move.ChangeTrackPieceMove

Documentation

No documentation available

Source Code

public TrackPiece getOldTrackPiece() {
return trackPieceBefore;
}

Called Methods

No outgoing method calls

testTrackPieceLegality

Class: jfreerails.world.track.TrackRule

Documentation

No documentation available

Source Code

boolean testTrackPieceLegality(int a9bitTemplate);

Called Methods

No outgoing method calls

nextStep

Class: jfreerails.controller.MoveTrainPreMove

Documentation

No documentation available

Source Code

Step nextStep(ReadOnlyWorld w) {
// Find current position.
TrainMotion currentMotion = lastMotion(w);
PositionOnTrack currentPosition = currentMotion.getFinalPosition();
// Find targets
ImPoint targetPoint = currentTrainTarget(w);
return findNextStep(w, currentPosition, targetPoint);
}

WorldImpl

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public WorldImpl(int mapWidth, int mapHeight) {
activityLists = new List3DImpl<ActivityAndTime>(0, 0);
bankAccounts = new List2DImpl<TransactionAndTimeStamp>(0);
currentBalance = new List1DImpl<Money>();
items = new List1DImpl<FreerailsSerializable>(ITEM.getNumberOfKeys());
lists = new List3DImpl<FreerailsSerializable>(0, KEY.getNumberOfKeys());
players = new List1DImpl<Player>();
sharedLists = new List2DImpl<FreerailsSerializable>(SKEY
.getNumberOfKeys());
time = GameTime.BIG_BANG;
setupItems();
setupMap(mapWidth, mapHeight);
}

testBoundsOnGet

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

public void testBoundsOnGet(){
underlying.addD1();
underlying.addD2(0, String.valueOf(1));
underlying.addD2(0, String.valueOf(2));
underlying.addD2(0, String.valueOf(3));
diffs.removeLastD2(0);
diffs.removeLastD2(0);
try {
assertEquals(1, diffs.size(0));
diffs.get(0, 2);
fail();
} catch (Exception e) {
}
}

getNumberOfActiveEntities

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

No documentation available

Source Code

int getNumberOfActiveEntities(FreerailsPrincipal p);

Called Methods

No outgoing method calls

TrainCellRenderer

Class: jfreerails.client.view.TrainCellRenderer

Documentation

No documentation available

Source Code

public TrainCellRenderer(RenderersRoot vl) {
rr = vl;
label = new JLabel();
}

Called Methods

No outgoing method calls

calcA

Class: jfreerails.world.train.SpeedAgainstTime

Documentation

/**
* @throws IllegalArgumentException
* iff t < 0 or t > getT()
*/

Source Code

/**
* @throws IllegalArgumentException
* iff t < 0 or t > getT()
*/
double calcA(double t);

Called Methods

No outgoing method calls

paintRect

Class: jfreerails.client.renderer.BufferedTiledBackgroundRenderer

Documentation

/**
* Updates the backbuffer as necessary, then draws it on to the Graphics
* object passed.
*
* @param outputGraphics
* Once it has been updated, the backbuffer is drawn onto this
* Graphics object.
* @param newVisibleRectangle
* The region of the map that the backbuffer must be updated to
* display.
*/

Source Code

/**
* Updates the backbuffer as necessary, then draws it on to the Graphics
* object passed.
*
* @param outputGraphics
* Once it has been updated, the backbuffer is drawn onto this
* Graphics object.
* @param newVisibleRectangle
* The region of the map that the backbuffer must be updated to
* display.
*/
public void paintRect(Graphics outputGraphics,
Rectangle newVisibleRectangle) {
do {
/*
* If this is the first call to the paint method or the component
* has just been resized, we need to create a new backgroundBuffer.
*/
if ((backgroundBuffer == null)
|| (newVisibleRectangle.height != bufferRect.height)
|| (newVisibleRectangle.width != bufferRect.width)) {
setbackgroundBuffer(newVisibleRectangle.width,
newVisibleRectangle.height);
}
// Test if image is lost and restore it.
int valCode = backgroundBuffer.validate(defaultConfig);
if (valCode == VolatileImage.IMAGE_INCOMPATIBLE) {
setbackgroundBuffer(newVisibleRectangle.width,
newVisibleRectangle.height);
} else if (valCode == VolatileImage.IMAGE_RESTORED) {
resetGraphics();
this.refreshBackground();
}
/*
* Has the VisibleRectangle moved since the last paint?
*/
if ((bufferRect.x != newVisibleRectangle.x)
|| (bufferRect.y != newVisibleRectangle.y)) {
int dx = bufferRect.x - newVisibleRectangle.x;
int dy = bufferRect.y - newVisibleRectangle.y;
scrollbackgroundBuffer(dx, dy);
bufferRect.setBounds(newVisibleRectangle);
}
if ((bufferRect.width != newVisibleRectangle.width)
&& (bufferRect.height != newVisibleRectangle.height)) {
paintBufferRectangle(newVisibleRectangle.x - bufferRect.x,
newVisibleRectangle.y - bufferRect.y,
newVisibleRectangle.width,
newVisibleRectangle.height);
}
outputGraphics.drawImage(backgroundBuffer,
newVisibleRectangle.x, newVisibleRectangle.y, null);
bufferRect.setBounds(newVisibleRectangle);
} while (backgroundBuffer.contentsLost());
}

dispatch

Class: jfreerails.server.parser.CargoAndTerrainParser

Documentation

No documentation available

Source Code

private void dispatch(final boolean fireOnlyIfMixed) throws SAXException {
if (fireOnlyIfMixed && buffer.length() == 0) {
return; // skip it
}
buffer.delete(0, buffer.length());
}

Called Methods

No outgoing method calls

testEqualsObject

Class: jfreerails.world.track.TrackPieceImplTest

Documentation

No documentation available

Source Code

public void testEqualsObject() {
TrackConfiguration tc1 = TrackConfiguration.getFlatInstance(Step.NORTH);
TrackRule rule0 = (TrackRule) w.get(SKEY.TRACK_RULES, 0);
TrackRule rule4 = (TrackRule) w.get(SKEY.TRACK_RULES, 4);
TrackPieceImpl tp1 = new TrackPieceImpl(tc1, rule0, 0, 0);
assertEquals(tp1, tp1);
TrackPieceImpl tp2 = new TrackPieceImpl(tc1, rule4, 0, 4);
assertFalse(tp1.equals(tp2));
TrackPieceImpl tp1Clone = (TrackPieceImpl) Utils
.cloneBySerialisation(tp1);
assertEquals(tp1, tp1Clone);
}

undoMove

Class: jfreerails.move.RemoveItemFromListMove

Documentation

No documentation available

Source Code

public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.isOk()) {
w.set(principal, listKey, index, this.item);
}
return ms;
}

add

Class: jfreerails.controller.OpenList

Documentation

No documentation available

Source Code

void add(int node, int f) {
if (map.containsKey(node)) {
OpenListEntry old = map.get(node);
queue.remove(old);
map.remove(node);
}
OpenList.OpenListEntry entry = new OpenListEntry(f, node);
queue.offer(entry);
map.put(node, entry);
}

Called Methods

No outgoing method calls

validate

Class: jfreerails.client.renderer.TileRendererListImpl

Documentation

No documentation available

Source Code

public boolean validate(ReadOnlyWorld w) {
// There should a TileRenderer for each terrain type.
return w.size(SKEY.TERRAIN_TYPES) == tiles.length;
}

calculate

Class: jfreerails.controller.StockPriceCalculator

Documentation

No documentation available

Source Code

public StockPrice[] calculate() {
StockPrice[] stockPrices = new StockPrice[w.getNumberOfPlayers()];
for (int playerId = 0; playerId < stockPrices.length; playerId++) {
long profitLastYear;
if(isFirstYear(playerId)){
profitLastYear = 100000;
}else{
profitLastYear = profitsLastYear(playerId);
}
long netWorth = netWorth(playerId);
int publicShares = sharesOwnedByPublic(playerId);
int otherRRShares = sharesOwnedByOtherPlayers(playerId);
stockPrices[playerId] = new StockPrice(netWorth, profitLastYear, publicShares, otherRRShares);
}
return stockPrices;
}

getDefault

Class: jfreerails.controller.BuildTrackStrategy

Documentation

No documentation available

Source Code

public static BuildTrackStrategy getDefault(ReadOnlyWorld w) {
ArrayList<Integer> allowable = new ArrayList<Integer>();
allowable.add(getCheapest(TrackRule.TrackCategories.track, w));
allowable.add(getCheapest(TrackRule.TrackCategories.bridge, w));
allowable.add(getCheapest(TrackRule.TrackCategories.tunnel, w));
return new BuildTrackStrategy(generateRules(allowable, w));
}

MappedButtonModel

Class: jfreerails.client.common.MappedButtonModel

Documentation

No documentation available

Source Code

public MappedButtonModel(Action action) {
actionName = (String) action.getValue(Action.NAME);
action.addPropertyChangeListener(this);
setEnabled(action.isEnabled());
}

Called Methods

No outgoing method calls

componentShown

Class: jfreerails.client.view.Unknown

Documentation

No documentation available

Source Code

@Override
public void componentShown(ComponentEvent e) {
int i = wi.getIndex();
wi.reset();
if (i != WorldIterator.BEFORE_FIRST) {
wi.gotoIndex(i);
}
display();
}

addConnection

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public synchronized void addConnection(Connection2Client connection) {
String[] before = getPlayerNames();
logger.fine("Adding connection..");
logger.fine("Waiting for login details..");
try {
LogOnRequest request = (LogOnRequest) connection
.waitForObjectFromClient();
logger.fine("Trying to login player: " + request.getUsername());
LogOnResponse response = this.logon(request);
connection.writeToClient(response);
connection.flush();
NameAndPassword p = new NameAndPassword(request.getUsername(),
request.getPassword());
if (response.isSuccessful()) {
logger.fine("Login successful");
synchronized (acceptedConnections) {
acceptedConnections.put(p, connection);
}
/* Just send to the new client. */
Message2Client setMaps = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.MAPS_AVAILABLE,
new ImStringList(savedGamesManager.getNewMapNames()));
ImStringList savedGameNames = new ImStringList(
savedGamesManager.getSaveGameNames());
Message2Client setSaveGames = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.SAVED_GAMES, savedGameNames);
connection.writeToClient(setMaps);
connection.writeToClient(setSaveGames);
// no need to flush since it is done in
// sendListOfConnectedPlayers2Clients()
/*
* If there is a game in progress, we need to send the client a
* copy of the world object.
*/
if (null != serverGameModel && null != getWorld()) {
SetWorldMessage2Client command = new SetWorldMessage2Client(
confirmationID, getWorld());
connection.writeToClient(command);
}
/* Send to all clients. */
sendListOfConnectedPlayers2Clients();
String[] after = getPlayerNames();
propertyChangeSupport.firePropertyChange("CONNECTED_PLAYERS",
before, after);
} else {
connection.disconnect();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

getCategory

Class: jfreerails.world.accounts.Bill

Documentation

No documentation available

Source Code

public Category getCategory() {
return category;
}

Called Methods

No outgoing method calls

saveProps

Class: jfreerails.launcher.LauncherInterface

Documentation

No documentation available

Source Code

void saveProps();

Called Methods

No outgoing method calls

setSize

Class: jfreerails.util.ArrayBase

Documentation

/**
* Sets the number of values currently present in the array. If the new size
* is greater than the current size, the added values are initialized to the
* default values. If the new size is less than the current size, all values
* dropped from the array are discarded.
*
* @param count
* number of values to be set
*/

Source Code

/**
* Sets the number of values currently present in the array. If the new size
* is greater than the current size, the added values are initialized to the
* default values. If the new size is less than the current size, all values
* dropped from the array are discarded.
*
* @param count
* number of values to be set
*/
public void setSize(int count) {
if (count > countLimit) {
growArray(count);
} else if (count < countPresent) {
discardValues(count, countPresent);
}
countPresent = count;
}

PathWalkerImplTest

Class: jfreerails.world.train.PathWalkerImplTest

Documentation

No documentation available

Source Code

public PathWalkerImplTest(String arg0) {
super(arg0);
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.common.ImHashSet

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ImHashSet))
return false;
final ImHashSet imHashSet = (ImHashSet) o;
if (!hashSet.equals(imHashSet.hashSet))
return false;
return true;
}

Called Methods

No outgoing method calls

removeLastD3

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

public T removeLastD3(int d1, int d2) {
return super.removeLast(d1, d2);
}

setup

Class: jfreerails.client.view.OverviewMapJComponent

Documentation

No documentation available

Source Code

public void setup(MapRenderer mv) {
mapView = mv;
this.setPreferredSize(mapView.getMapSizeInPixels());
this.setMinimumSize(this.getPreferredSize());
this.setSize(this.getPreferredSize());
if (null != this.getParent()) {
this.getParent().validate();
}
}

setUp

Class: jfreerails.move.WorldDiffsMoveTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
world = new WorldImpl(10, 10);
// Set the time..
world.set(ITEM.CALENDAR, new GameCalendar(12000, 1840));
world.addPlayer(MapFixtureFactory.TEST_PLAYER);
fp1 = world.getPlayer(0).getPrincipal();
diffs = new WorldDiffs(world);
}

planBuildingTrack

Class: jfreerails.client.renderer.BuildTrackController

Documentation

/**
* Attempts to building track from the specified point in the specified
* direction on the worldDiff object.
*/

Source Code

/**
* Attempts to building track from the specified point in the specified
* direction on the worldDiff object.
*/
private MoveStatus planBuildingTrack(ImPoint point, Step vector) {
FreerailsTile tileA = (FreerailsTile) worldDiffs.getTile(point.x,
point.y);
BuildTrackStrategy bts = getBts();
int trackTypeAID = bts.getRule(tileA.getTerrainTypeID());
TrackRule trackRuleA = (TrackRule) worldDiffs.get(SKEY.TRACK_RULES,
trackTypeAID);
FreerailsTile tileB = (FreerailsTile) worldDiffs.getTile(point.x
+ vector.deltaX, point.y + vector.deltaY);
int trackTypeBID = bts.getRule(tileB.getTerrainTypeID());
TrackRule trackRuleB = (TrackRule) worldDiffs.get(SKEY.TRACK_RULES,
trackTypeBID);
ChangeTrackPieceCompositeMove move = ChangeTrackPieceCompositeMove
.generateBuildTrackMove(point, vector, trackRuleA, trackRuleB,
worldDiffs, principal);
return move.doMove(worldDiffs, principal);
}

getSpeedAtEnd

Class: jfreerails.world.train.TrainMotion

Documentation

No documentation available

Source Code

public double getSpeedAtEnd() {
double finalT = speeds.getT();
return speeds.calcV(finalT);
}

canConnect2OtherRRsTrack

Class: jfreerails.move.ChangeTrackPieceMove

Documentation

No documentation available

Source Code

protected static boolean canConnect2OtherRRsTrack(ReadOnlyWorld world) {
GameRules rules = (GameRules) world.get(ITEM.GAME_RULES);
return rules.isCanConnect2OtherRRTrack();
}

setVisible

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

No documentation available

Source Code

private void setVisible(boolean track, boolean bridges, boolean tunnels,
boolean stations) {
trackJPanel.setVisible(bridges);
bridgesJPanel.setVisible(bridges);
tunnelsJPanel.setVisible(tunnels);
stationsJPanel.setVisible(stations);
}

Called Methods

No outgoing method calls

testContains

Class: jfreerails.controller.OpenListTest

Documentation

No documentation available

Source Code

public void testContains() {
OpenList openList = new OpenList();
assertFalse(openList.contains(0));
openList.add(0, 4);
assertTrue(openList.contains(0));
assertFalse(openList.contains(4));
openList.popNodeWithSmallestF();
assertFalse(openList.contains(0));
}

toServer

Class: jfreerails.network.specifics.MovePrecommitter

Documentation

No documentation available

Source Code

Move toServer(PreMove pm) {
uncomitted.addLast(pm);
precommitMoves();
if (blocked) {
return pm.generateMove(w);
}
PreMoveAndMove pmam = (PreMoveAndMove) precomitted.getLast();
return pmam.m;
}

assertUndoMoveFails

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

protected void assertUndoMoveFails(Move m) {
assertSetupHasBeenCalled();
MoveStatus ms = m.tryUndoMove(getWorld(), Player.AUTHORITATIVE);
assertNotNull(ms);
assertTrue("Move went through when it should have failed", !ms.ok);
}

getBuildTrackController

Class: jfreerails.client.view.DetailMapRenderer

Documentation

No documentation available

Source Code

public BuildTrackController getBuildTrackController() {
return buildTrackController;
}

Called Methods

No outgoing method calls

formMouseClicked

Class: jfreerails.client.view.SelectStationJPanel

Documentation

No documentation available

Source Code

private void formMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_formMouseClicked
formMouseMoved(evt);
needsUpdating = true;
this.submitButtonCallBack.actionPerformed(null);
}// GEN-LAST:event_formMouseClicked

autoConsist

Class: jfreerails.world.train.MutableSchedule

Documentation

No documentation available

Source Code

public boolean autoConsist() {
return orders.get(nextScheduledOrder).autoConsist;
}

Called Methods

No outgoing method calls

move

Class: jfreerails.move.ChangeTrackPieceMove

Documentation

No documentation available

Source Code

private void move(World w, TrackPiece oldTrackPiece,
TrackPiece newTrackPiece) {
// FIXME why is oldTrackPiece not used???
FreerailsTile oldTile = (FreerailsTile) w.getTile(location.x,
location.y);
int terrain = oldTile.getTerrainTypeID();
FreerailsTile newTile = FreerailsTile.getInstance(terrain,
newTrackPiece);
w.setTile(location.x, location.y, newTile);
}

hideAllMessages

Class: jfreerails.launcher.Launcher

Documentation

No documentation available

Source Code

public void hideAllMessages() {
infoLabel.setText(null);
infoLabel.setIcon(null);
nextButton.setEnabled(true);
}

Called Methods

No outgoing method calls

IncomeStatementGenerator

Class: jfreerails.client.view.IncomeStatementGenerator

Documentation

No documentation available

Source Code

IncomeStatementGenerator(ReadOnlyWorld w, FreerailsPrincipal principal) {
this.w = w;
this.principal = principal;
cal = (GameCalendar) w.get(ITEM.CALENDAR);
// Income from cargo delivery
mailTotal = calRevenue(Categories.Mail);
passengersTotal = calRevenue(Categories.Passengers);
fastFreightTotal = calRevenue(Categories.Fast_Freight);
slowFreightTotal = calRevenue(Categories.Slow_Freight);
bulkFreightTotal = calRevenue(Categories.Bulk_Freight);
// Expenses.
interestTotal = calTotal(INTEREST_CHARGE);
trainMaintenanceTotal = calTotal(TRAIN_MAINTENANCE);
trackMaintenanceTotal = calTotal(TRACK_MAINTENANCE);
stationMaintenanceTotal = calTotal(STATION_MAINTENANCE);
/*
* Note, expenses are stored as negative values so we just add
* everything up.
*/
long profit = mailTotal.getAmount() + passengersTotal.getAmount()
+ fastFreightTotal.getAmount() + slowFreightTotal.getAmount()
+ bulkFreightTotal.getAmount() + interestTotal.getAmount()
+ trainMaintenanceTotal.getAmount()
+ trackMaintenanceTotal.getAmount()
+ stationMaintenanceTotal.getAmount();
profitTotal = new Money(profit);
GameTime time = w.currentTime();
startyear = cal.getYear(time.getTicks());
year = String.valueOf(startyear);
// Income from cargo delivery
mailYtd = calRevenue(Categories.Mail);
passengersYtd = calRevenue(Categories.Passengers);
fastFreightYtd = calRevenue(Categories.Fast_Freight);
slowFreightYtd = calRevenue(Categories.Slow_Freight);
bulkFreightYtd = calRevenue(Categories.Bulk_Freight);
// Expenses.
interestYtd = calTotal(INTEREST_CHARGE);
trainMaintenanceYtd = calTotal(TRAIN_MAINTENANCE);
trackMaintenanceYtd = calTotal(TRACK_MAINTENANCE);
stationMaintenanceYtd = calTotal(STATION_MAINTENANCE);
/*
* Note, expenses are stored as negative values so we just add
* everything up.
*/
profit = mailYtd.getAmount() + passengersYtd.getAmount()
+ fastFreightYtd.getAmount() + slowFreightYtd.getAmount()
+ bulkFreightYtd.getAmount() + interestYtd.getAmount()
+ trainMaintenanceYtd.getAmount()
+ trackMaintenanceYtd.getAmount()
+ stationMaintenanceYtd.getAmount();
profitYtd = new Money(profit);
}

addListListener

Class: jfreerails.network.specifics.MoveChainFork

Documentation

No documentation available

Source Code

public void addListListener(WorldListListener listener) {
if (null == listener) {
throw new NullPointerException();
}
listListeners.add(listener);
}

Called Methods

No outgoing method calls

size

Class: jfreerails.world.top.NonNullElements

Documentation

No documentation available

Source Code

public int size() {
if (-1 == size) { // lazy loading, if we have already calculated the
// size don't do it again.
int tempSize = 0;
for (int i = 0; i < listSize(); i++) {
if (null != listGet(i)) {
tempSize++;
}
}
size = tempSize;
}
return size;
}

MessageStatus

Class: jfreerails.controller.MessageStatus

Documentation

No documentation available

Source Code

public MessageStatus(int id, boolean successful) {
this.id = id;
this.reason = null;
this.successful = successful;
}

Called Methods

No outgoing method calls

autoConsist

Class: jfreerails.world.train.ImmutableSchedule

Documentation

No documentation available

Source Code

public boolean autoConsist() {
TrainOrdersModel order = orders.get(getOrderToGoto());
return order.autoConsist;
}

IntArray

Class: jfreerails.util.IntArray

Documentation

/**
* Constructor with only initial size specified.
*
* @param size
* number of <code>int</code> values initially allowed in array
*/

Source Code

/**
* Constructor with only initial size specified.
*
* @param size
* number of <code>int</code> values initially allowed in array
*/
public IntArray(int size) {
super(size, int.class);
}

removeButtons

Class: jfreerails.client.view.TrainListJPanel

Documentation

/** When the train list is shown on a tab we don't want the buttons. */

Source Code

/** When the train list is shown on a tab we don't want the buttons. */
void removeButtons() {
this.removeAll();
java.awt.GridBagConstraints gridBagConstraints;
setLayout(new java.awt.GridBagLayout());
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(jScrollPane1, gridBagConstraints);
}

Called Methods

No outgoing method calls

SimplePathIteratorImpl

Class: jfreerails.world.train.SimplePathIteratorImpl

Documentation

No documentation available

Source Code

public SimplePathIteratorImpl( /* =const */
int[] xpoints, /* =const */
int[] ypoints) {
x = new ImInts(xpoints);
y = new ImInts(ypoints); // defensive copy.
if (x.size() != y.size()) {
throw new IllegalArgumentException(
"The array length of the array must be even");
}
}

setVisible

Class: jfreerails.client.top.StationTypesPopup

Documentation

No documentation available

Source Code

@Override
public void setVisible(boolean b) {
// If this popup is visible, we don't want the station's position to
// follow the mouse.
stationBuildModel.setPositionFollowsMouse(!b);
super.setVisible(b);
}

setTrainTabEnabled

Class: jfreerails.client.view.RHSJTabPane

Documentation

No documentation available

Source Code

public void setTrainTabEnabled(boolean enabled) {
this.setEnabledAt(this.trainListIndex, enabled);
}

Called Methods

No outgoing method calls

getDemand

Class: jfreerails.controller.CalcCargoSupplyRateAtStation

Documentation

No documentation available

Source Code

public Demand4Cargo getDemand() {
boolean[] demandboolean = new boolean[w.size(SKEY.CARGO_TYPES)];
for (int i = 0; i < w.size(SKEY.CARGO_TYPES); i++) {
if (demand[i] >= PREREQUISITE_FOR_DEMAND) {
demandboolean[i] = true;
}
}
return new Demand4Cargo(demandboolean);
}

assertLineEquals

Class: jfreerails.world.train.PathWalkerImplTest

Documentation

No documentation available

Source Code

private void assertLineEquals(int x1, int y1, int x2, int y2, IntLine line) {
assertEquals(x1, line.x1);
assertEquals(x2, line.x2);
assertEquals(y1, line.y1);
assertEquals(y2, line.y2);
}

Called Methods

No outgoing method calls

TrainOrdersModel

Class: jfreerails.world.train.TrainOrdersModel

Documentation

No documentation available

Source Code

public TrainOrdersModel(int station, ImInts newConsist, boolean wait,
boolean auto) {
// If there are no wagons, set wait = false.
wait = (null == newConsist || 0 == newConsist.size()) ? false : wait;
this.waitUntilFull = wait;
this.consist = newConsist;
this.stationId = station;
this.autoConsist = auto;
}

TrainModel

Class: jfreerails.world.train.TrainModel

Documentation

No documentation available

Source Code

public TrainModel(int engine, ImInts wagons, int scheduleID) {
engineTypeId = engine;
wagonTypes = wagons;
scheduleId = scheduleID;
cargoBundleId = 0;
}

Called Methods

No outgoing method calls

getMapWidth

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public int getMapWidth() {
return map.length;
}

Called Methods

No outgoing method calls

ImList

Class: jfreerails.world.common.ImList

Documentation

No documentation available

Source Code

@SuppressWarnings("unchecked")
public ImList(List<E> list) {
elementData = (E[]) new FreerailsSerializable[list.size()];
for (int i = 0; i < list.size(); i++) {
elementData[i] = list.get(i);
}
}

Called Methods

No outgoing method calls

getEdgeCost

Class: jfreerails.controller.GraphExplorer

Documentation

/** Returns the cost of the current edge. */

Source Code

/** Returns the cost of the current edge. */
int getEdgeCost();

Called Methods

No outgoing method calls

getDrawGraphics

Class: jfreerails.controller.ScreenHandler

Documentation

No documentation available

Source Code

public synchronized Graphics getDrawGraphics() {
return bufferStrategy.getDrawGraphics();
}

Called Methods

No outgoing method calls

ListKey

Class: jfreerails.util.ListKey

Documentation

No documentation available

Source Code

public ListKey(Type t, Enum listID, int... i){
type = t;
index = i.clone();
this.listID = listID;
}

Called Methods

  • _Dummy_.__Array__.clone (external)

testCondition

Class: jfreerails.world.top.NonNullElements

Documentation

No documentation available

Source Code

protected boolean testCondition(int i) {
return null != listGet(i);
}

worsen

Class: jfreerails.controller.FinancialMoveProducer

Documentation

No documentation available

Source Code

EconomicClimate worsen() {
return null;
}

Called Methods

No outgoing method calls

tryDoMove

Class: jfreerails.move.ChangeTrackPieceMove

Documentation

No documentation available

Source Code

public MoveStatus tryDoMove(World w, FreerailsPrincipal p) {
return tryMove(w, this.trackPieceBefore, this.trackPieceAfter);
}

listUpdated

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

public void listUpdated(KEY key, int index, FreerailsPrincipal principal) {
boolean rightPrincipal = principal
.equals(this.modelRoot.getPrincipal());
if (KEY.TRAINS == key && rightPrincipal) {
countTrains();
} else if (KEY.STATIONS == key && rightPrincipal) {
countStations();
}
}

getElementAt

Class: jfreerails.client.view.DisplayModesComboBoxModels

Documentation

No documentation available

Source Code

public MyDisplayMode getElementAt(int index) {
return modes.get(index);
}

Called Methods

No outgoing method calls

getY

Class: jfreerails.server.RandomTerrainValue

Documentation

No documentation available

Source Code

public int getY() {
return y;
}

Called Methods

No outgoing method calls

test3DList

Class: jfreerails.util.ListXDTest

Documentation

No documentation available

Source Code

public void test3DList(){
list3d = new List3DImpl<Object>(0, 0);
//Add a player
int playerId = list3d.addD1();
list3d.addD2(playerId);
list3d.addD2(playerId);
list3d.addD2(playerId);
//Then remove them
while(list3d.sizeD2(playerId)>0){
list3d.removeLastD2(playerId);
}
}

removeLastPlayer

Class: jfreerails.world.top.World

Documentation

No documentation available

Source Code

Player removeLastPlayer();

Called Methods

No outgoing method calls

distSquared

Class: experimental.DistanceComparator

Documentation

No documentation available

Source Code

int distSquared(CityModel a) {
int xDist = a.getCityX() - targetX;
int yDist = a.getCityY() - targetY;
return xDist * xDist + yDist * yDist;
}

getSubclassesOf

Class: jfreerails.util.ClassLocater

Documentation

/**
* Find all subclasses of the given <code>Class</code> or interface by
* loading only those classes with names that match the given regular
* expression.
* <P>
* Once all classes have been checked, it will output at WARN a list of all
* the classes that were referenced by other classes but are not installed
* in the classpath. This can be incredibly useful - it catches situations
* where e.g. you thought a class was on the classpath but you put it in the
* wrong directory etc.
* <P>
* It can also be very annoying because java uses dynamic linking so it is
* LEGAL for many classes to be missing, just so long as you never use them
* at runtime. Because this class tries to use *every* class, it triggers
* errors on lots that you don't care about - use addSkipPrefix( class or
* package you dont use even though its on the classpath ) and they will be
* skipped (i.e. not even examined by this method).
* <P>
* OR improve your regex so that it is more selective about the packages
* where your classes could conceivable be located!
*
* @param targetType
* the superclass of all returned classes.
* @param regex
* a regular expression that will match with every subclass
* @return an array of all subclasses of <code>targetType</code>
*/

Source Code

/**
* Find all subclasses of the given <code>Class</code> or interface by
* loading only those classes with names that match the given regular
* expression.
* <P>
* Once all classes have been checked, it will output at WARN a list of all
* the classes that were referenced by other classes but are not installed
* in the classpath. This can be incredibly useful - it catches situations
* where e.g. you thought a class was on the classpath but you put it in the
* wrong directory etc.
* <P>
* It can also be very annoying because java uses dynamic linking so it is
* LEGAL for many classes to be missing, just so long as you never use them
* at runtime. Because this class tries to use *every* class, it triggers
* errors on lots that you don't care about - use addSkipPrefix( class or
* package you dont use even though its on the classpath ) and they will be
* skipped (i.e. not even examined by this method).
* <P>
* OR improve your regex so that it is more selective about the packages
* where your classes could conceivable be located!
*
* @param targetType
* the superclass of all returned classes.
* @param regex
* a regular expression that will match with every subclass
* @return an array of all subclasses of <code>targetType</code>
*/
@SuppressWarnings("unchecked")
public Class[] getSubclassesOf(Class targetType, String regex) {
logger.info("Looking for all classes with names matching regex = "
+ regex + " and which are subtypes of " + targetType.getName());
StringBuffer sbSkips = new StringBuffer();
for (Iterator i2 = skipPrefixes.iterator(); i2.hasNext();) {
sbSkips.append(i2.next().toString() + "*");
if (i2.hasNext())
sbSkips.append(", ");
}
logger.info("...unless they match: " + sbSkips.toString());
LinkedList<Class> matches = new LinkedList<Class>();
HashMap<String, LinkedList<String>> missingRequiredClasses = new HashMap<String, LinkedList<String>>();
// maps class name to list of classes that needed it
logger.fine("Creating ClassPath object to do class search...");
ClassPath cp = new ClassPath();
logger.fine("Iterating through all classes in ClassPath...");
for (Iterator iter = cp.getAllClassNames().iterator(); iter.hasNext();) {
String className = (String) iter.next();
boolean skip = false;
for (Iterator i2 = skipPrefixes.iterator(); i2.hasNext();) {
String prefix = (String) i2.next();
if (className.startsWith(prefix)) {
logger.fine("Skipping class = " + className
+ " because it has a prefix of " + prefix);
skip = true;
break;
}
}
if (skip)
continue;
logger.fine("Processing class: " + className);
if (className.matches(regex)
&& !className.equals(targetType.getName())) {
logger
.fine("...matches regex; instantiating and checking type");
Class clazz = null;
try {
clazz = Class.forName(className);
}
/*
* catch (ClassNotFoundException cnfx ) { continue; }
*/
catch (NoClassDefFoundError cnfx) {
/*
* This is ridiculous. Please, everyone, ask sun to add a
* "getMissingClass()" method to NoClassDefFoundError: Sun,
* you have had TEN YEARS to fix this!
*/
if (cnfx.getMessage() == null) {
logger
.log(
Level.WARNING,
"NoClassDefFoundError but Sun didn't fill-in the message; no idea which class it was; ignoring it and moving on",
cnfx);
continue;
}
String missingClassName = cnfx.getMessage().replace('/',
'.');
LinkedList<String> misses = missingRequiredClasses
.get(missingClassName);
if (misses == null) {
misses = new LinkedList<String>();
missingRequiredClasses.put(missingClassName, misses);
}
misses.add(className);
continue;
} catch (UnsatisfiedLinkError cnfx) {
continue;
} catch (Throwable t) {
logger.log(Level.WARNING,
"Unexpected error - REMOVING this class ("
+ className + ") without checking it", t);
continue;
} finally {
if (clazz != null && targetType.isAssignableFrom(clazz)) {
logger
.fine(className
+ " matches and is correct type; adding to results");
matches.add(clazz);
}
}
}
}
if (missingRequiredClasses.size() > 0) {
logger
.warning("The following classes were needed by some of the classes I found, but could not themselves be found."
+ "Check you have the required libraries, that they are on the classpath, and that all JAR's are in your manifest as needed");
logger
.warning("If you don't care about some of the classes that used these missing classes, add the users to the skip list and you will get no errors from them");
for (Iterator<String> iter = missingRequiredClasses.keySet()
.iterator(); iter.hasNext();) {
String className = iter.next();
LinkedList<String> neededBy = missingRequiredClasses
.get(className);
StringBuffer sb = new StringBuffer();
for (Iterator<String> iterator = neededBy.iterator(); iterator
.hasNext();) {
String referencingClass = iterator.next();
sb.append(referencingClass);
if (iterator.hasNext())
sb.append(", ");
}
logger.warning("class: " + className + " was needed by class"
+ (neededBy.size() == 1 ? "" : "es") + ": " + sb);
}
}
logger.info("found " + matches.size() + " classes.");
return matches.toArray(new Class[matches.size()]);
}

bulldozeActionPerformed

Class: jfreerails.client.view.BuildTrackJPanel

Documentation

No documentation available

Source Code

private void bulldozeActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_bulldozeActionPerformed
setVisible(false, false, false, false);
cancelStationPlacement();
setTrackBuilderMode(REMOVE_TRACK);
}// GEN-LAST:event_bulldozeActionPerformed

readFromClient

Class: jfreerails.network.LocalConnection

Documentation

No documentation available

Source Code

public FreerailsSerializable[] readFromClient() throws IOException {
if (status.isOpen()) {
return fromClient.read();
}
throw new IOException();
}

getZipContents

Class: jfreerails.util.ClassPath

Documentation

/**
* Adds all class names found in the zip mentioned
*
* @param zipFile
*/

Source Code

/**
* Adds all class names found in the zip mentioned
*
* @param zipFile
*/
protected LinkedList<String> getZipContents(File zipFile) {
LinkedList<String> result = new LinkedList<String>();
ZipFile zip = null;
try {
zip = new JarFile(zipFile);
} catch (IOException iox) {
}
if (zip != null) {
Enumeration e = zip.entries();
while (e.hasMoreElements()) {
ZipEntry entry = (ZipEntry) e.nextElement();
if (!entry.isDirectory() && entry.getName().endsWith(".class")) {
String className = getClassNameFrom(entry.getName());
result.add(className);
}
}
}
return result;
}

removeListDataListener

Class: jfreerails.client.view.World2ListModelAdapter

Documentation

No documentation available

Source Code

public void removeListDataListener(ListDataListener arg0) {
// TODO Auto-generated method stub
}

Called Methods

No outgoing method calls

hasNextInt

Class: jfreerails.util.FreerailsIntIterator

Documentation

No documentation available

Source Code

boolean hasNextInt();

Called Methods

No outgoing method calls

setUp

Class: jfreerails.client.view.BrokerScreenGeneratorTest

Documentation

No documentation available

Source Code

@Override
protected void setUp() throws Exception {
// TODO Auto-generated method stub
super.setUp();
world = new WorldImpl(10, 10);
// Set the time..
world.set(ITEM.CALENDAR, new GameCalendar(12000, 1840));
Player p = MapFixtureFactory.TEST_PLAYER;
AddPlayerMove apm = AddPlayerMove.generateMove(world, p);
MoveStatus ms = apm.doMove(world, Player.AUTHORITATIVE);
assertTrue(ms.isOk());
playerID = world.getNumberOfPlayers() - 1;
principal = p.getPrincipal();
}

getYearAsString

Class: jfreerails.world.common.GameCalendar

Documentation

No documentation available

Source Code

public String getYearAsString(int ticks) {
int i = getYear(ticks);
return String.valueOf(i);
}

hashCode

Class: jfreerails.network.specifics.LogOnResponse

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = (successful ? 1 : 0);
result = 29 * result + playerNumber;
result = 29 * result + (message != null ? message.hashCode() : 0);
return result;
}

Called Methods

No outgoing method calls

setPathToWriteTo

Class: jfreerails.client.common.ImageManagerImpl

Documentation

No documentation available

Source Code

public void setPathToWriteTo(String s) {
pathToWriteTo = s;
}

Called Methods

No outgoing method calls

List3DImpl

Class: jfreerails.util.List3DImpl

Documentation

No documentation available

Source Code

public List3DImpl(int d1, int d2){
for (int i = 0; i < d1; i++) {
ArrayList<ArrayList<T>> dim2 = new ArrayList<ArrayList<T>>();
elementData.add(dim2);
for (int j = 0; j < d2; j++) {
dim2.add(new ArrayList<T>() );
}
}
}

Called Methods

No outgoing method calls

overallRate

Class: jfreerails.util.FlowRateInputStream

Documentation

No documentation available

Source Code

public int overallRate() {
return (int) (totalByteReceived / 1024D / ((System.currentTimeMillis() - openTimeMillis) / 1000D));
}

Called Methods

No outgoing method calls

testPreMoves2

Class: jfreerails.network.specifics.MovePrecommitterTest

Documentation

No documentation available

Source Code

public void testPreMoves2() {
PreMove pm = TimeTickPreMove.INSTANCE;
GameTime oldtime = getTime();
GameTime newTime = oldtime.nextTick();
// Send a premove to the server.
committer.toServer(pm);
assertEquals(0, committer.uncomitted.size());
assertEquals(1, committer.precomitted.size());
assertEquals(newTime, getTime());
// The server accepts it..
committer.fromServer(PreMoveStatus.PRE_MOVE_OK);
assertEquals(0, committer.uncomitted.size());
assertEquals(0, committer.precomitted.size());
assertEquals(newTime, getTime());
}

itemAdded

Class: jfreerails.world.top.WorldListListener

Documentation

No documentation available

Source Code

void itemAdded(KEY key, int index, FreerailsPrincipal principal);

Called Methods

No outgoing method calls

isCargoConverted

Class: jfreerails.world.station.ConvertedAtStation

Documentation

No documentation available

Source Code

public boolean isCargoConverted(int cargoNumber) {
if (NOT_CONVERTED == convertedTo.get(cargoNumber)) {
return false;
}
return true;
}

testHasNext

Class: jfreerails.world.train.SimplePathIteratorImplTest

Documentation

No documentation available

Source Code

public void testHasNext() {
int[] xpoints = { 0, 100 };
int[] ypoints = { 0, 0 };
FreerailsPathIterator it = new SimplePathIteratorImpl(xpoints, ypoints);
assertTrue(it.hasNext());
it.nextSegment(new IntLine(0, 0, 0, 0));
assertTrue(!it.hasNext());
}

get

Class: jfreerails.util.List3DImpl

Documentation

No documentation available

Source Code

public T get(int d1, int d2, int d3) {
return elementData.get(d1).get(d2).get(d3);
}

Called Methods

No outgoing method calls

TypeID

Class: jfreerails.world.top.TypeID

Documentation

No documentation available

Source Code

public TypeID(int id, SKEY key) {
this.id = id;
this.key = key;
}

Called Methods

No outgoing method calls

paintBufferRectangle

Class: jfreerails.client.renderer.BufferedTiledBackgroundRenderer

Documentation

No documentation available

Source Code

protected abstract void paintBufferRectangle(int x, int y, int width,
int height);

Called Methods

No outgoing method calls

finished

Class: jfreerails.launcher.GUIClient

Documentation

No documentation available

Source Code

public void finished() {
// TODO Auto-generated method stub
}

Called Methods

No outgoing method calls

CalcSupplyAtStations

Class: jfreerails.server.CalcSupplyAtStations

Documentation

/**
*
* Constructor, currently called from GUIComponentFactory.
*
* @param world
* The World object that contains all about the game world
*
*/

Source Code

/**
*
* Constructor, currently called from GUIComponentFactory.
*
* @param world
* The World object that contains all about the game world
*
*/
public CalcSupplyAtStations(World world, MoveReceiver mr) {
this.w = world;
this.moveReceiver = mr;
}

Called Methods

No outgoing method calls

testClose

Class: jfreerails.network.LocalConnectionTest

Documentation

No documentation available

Source Code

public void testClose() {
try {
localConnection.disconnect();
Money m = new Money(100);
localConnection.writeToClient(m);
fail();
} catch (Exception e) {
}
}

StationModel

Class: jfreerails.world.station.StationModel

Documentation

No documentation available

Source Code

public StationModel(StationModel s, ConvertedAtStation converted) {
this.converted = converted;
this.cargoBundleNumber = s.cargoBundleNumber;
this.demand = s.demand;
this.name = s.name;
this.production = s.production;
this.supply = s.supply;
this.x = s.x;
this.y = s.y;
}

Called Methods

No outgoing method calls

setupLoopOfTrack

Class: jfreerails.controller.MoveTrainPreMove1stTest

Documentation

No documentation available

Source Code

private void setupLoopOfTrack() {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
TrackMoveProducer producer = new TrackMoveProducer(me, world, mr);
Step[] trackPath = { EAST, SOUTH_EAST, SOUTH, SOUTH_WEST, WEST,
NORTH_WEST, NORTH, NORTH_EAST };
ImPoint from = new ImPoint(5, 5);
MoveStatus ms = producer.buildTrack(from, trackPath);
assertTrue(ms.ok);
TrainOrdersModel[] orders = {};
ImmutableSchedule is = new ImmutableSchedule(orders, -1, false);
AddTrainPreMove addTrain = new AddTrainPreMove(0, new ImInts(), from,
principal, is);
Move m = addTrain.generateMove(world);
ms = m.doMove(world, principal);
assertTrue(ms.ok);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
TrainMotion motion = ta.findCurrentMotion(0);
assertNotNull(motion);
PathOnTiles expected = new PathOnTiles(from, SOUTH_WEST);
PathOnTiles actual = motion.getTiles(motion.duration());
assertEquals(expected, actual);
}

removeLast

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public FreerailsSerializable removeLast(SKEY key) {
return sharedLists.removeLastD2(key.getKeyID());
}

getH

Class: jfreerails.controller.Map

Documentation

No documentation available

Source Code

public int getH() {
// TODO Auto-generated method stub
return 0;
}

Called Methods

No outgoing method calls

update

Class: jfreerails.server.ServerGameModelImpl

Documentation

/**
*
*/

Source Code

/**
*
*/
public synchronized void update() {
long frameStartTime = System.currentTimeMillis();
while (nextModelUpdateDue <= frameStartTime) {
/*
* First do the things that need doing whether or not the game is
* paused.
*/
tb.buildTrains(world);
int gameSpeed = ((GameSpeed) world.get(ITEM.GAME_SPEED)).getSpeed();
if (gameSpeed > 0) {
/*
* Update the time first, since other updates might need to know
* the current time.
*/
updateGameTime();
// now do the other updates
tb.moveTrains(world);
// Check whether we are about to start a new year..
GameTime time = world.currentTime();
GameCalendar calendar = (GameCalendar) world.get(ITEM.CALENDAR);
int yearNextTick = calendar.getYear(time.getTicks() + 1);
int yearThisTick = calendar.getYear(time.getTicks());
if (yearThisTick != yearNextTick) {
yearEnd();
}
// And a new month..
int monthThisTick = calendar.getMonth(time.getTicks());
int monthNextTick = calendar.getMonth(time.getTicks() + 1);
if (monthNextTick != monthThisTick) {
monthEnd();
}
/* calculate "ideal world" time for next tick */
nextModelUpdateDue = nextModelUpdateDue + (1000 / gameSpeed);
// int delay = (int)(nextModelUpdateDue - frameStartTime);
//
// /* wake up any waiting client threads - we could be
// * more aggressive, and only notify them if delay > 0? */
// this.notifyAll();
//
// try {
// if (delay > 0) {
// this.wait(delay);
// } else {
// this.wait(1);
// }
// } catch (InterruptedException e) {
// // do nothing
// }
ticksSinceUpdate++;
} else {
// try {
// //When the game is frozen we don't want to be spinning in a
// //loop.
// Thread.sleep(200);
// } catch (InterruptedException e) {
// // do nothing
// }
nextModelUpdateDue = System.currentTimeMillis();
}
}
}

getTrainRenderer

Class: jfreerails.client.view.DetailMapRenderer

Documentation

No documentation available

Source Code

public TrainRenderer getTrainRenderer() {
return this.trainsview.getTrainRenderer();
}

getAmount

Class: jfreerails.world.cargo.CargoBundle

Documentation

No documentation available

Source Code

int getAmount(CargoBatch cb);

Called Methods

No outgoing method calls

setTargetPoint

Class: jfreerails.client.renderer.BuildTrackController

Documentation

/**
* @param newTargetPoint
* The m_targetPoint to set.
*/

Source Code

/**
* @param newTargetPoint
* The m_targetPoint to set.
*/
private void setTargetPoint(ImPoint newTargetPoint) {
this.targetPoint = newTargetPoint;
ImPoint p = null == newTargetPoint ? null : newTargetPoint;
modelRoot.setProperty(ModelRoot.Property.THINKING_POINT, p);
}

SpeedTimeAndStatus

Class: jfreerails.world.train.SpeedTimeAndStatus

Documentation

No documentation available

Source Code

SpeedTimeAndStatus(double acceleration, TrainActivity activity, double dt,
double s, double speed) {
if (dt < 0)
throw new IllegalArgumentException(String.valueOf(dt));
this.acceleration = acceleration;
this.activity = activity;
this.dt = dt;
this.s = s;
this.speed = speed;
}

Called Methods

No outgoing method calls

previousActivity

Class: jfreerails.world.common.ActivityIterator

Documentation

No documentation available

Source Code

void previousActivity() throws NoSuchElementException;

Called Methods

No outgoing method calls

testAddD1

Class: jfreerails.util.List2DDiffTest

Documentation

No documentation available

Source Code

/*
* Test method for 'jfreerails.util.List2DDiff.addD1()'
*/
public void testAddD1() {
underlying.addD1();
assertEquals(1, diffs.sizeD1());
assertEquals(1, diffs.getUnderlyingSize());
assertEquals(1, diffs.size());
diffs.addD1();
ListKey sizeKey = new ListKey(EndPoint, listid.test);
assertEquals(2, map.size());
assertTrue(map.containsKey(sizeKey));
assertEquals(new Integer(2), map.get(sizeKey));
assertEquals(2, diffs.sizeD1());
diffs.addD1();
assertEquals(3, diffs.sizeD1());
}

ClassPath

Class: jfreerails.util.ClassPath

Documentation

/**
* create a new ClassPath instance and find all classes on the classpath
*/

Source Code

/**
* create a new ClassPath instance and find all classes on the classpath
*/
public ClassPath() {
}

Called Methods

No outgoing method calls

enableAndDisableActions

Class: jfreerails.client.view.BrokerScreenHtmlJFrame

Documentation

No documentation available

Source Code

private void enableAndDisableActions(){
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal p = modelRoot.getPrincipal();
FinancialDataGatherer thisDataGatherer = new FinancialDataGatherer(
world, p);
StockPrice[] stockPrices = new StockPriceCalculator(world).calculate();
long highestAffordablePrice = world.getCurrentBalance(p).getAmount() / StockTransaction.STOCK_BUNDLE_SIZE;
//Enable and disable stock actions.
for(int playerId = 0; playerId < world.getNumberOfPlayers(); playerId++){
Player temp = modelRoot.getWorld().getPlayer(playerId);
FreerailsPrincipal otherPrincipal = temp.getPrincipal();
FinancialDataGatherer otherDataGatherer = new FinancialDataGatherer(world, otherPrincipal);
//If this RR has stock in other RR, then enable sell stock
boolean hasStockInRR = thisDataGatherer.getStockInRRs()[playerId] > 0;
sellStock[playerId].setEnabled(hasStockInRR);
//If the public own some stock, then enable buy stock.
boolean isStockAvailable = otherDataGatherer.sharesHeldByPublic() > 0;
buyStock[playerId].setEnabled(isStockAvailable);
//Don't let player buy 100% of treasury stock.
if(otherPrincipal.equals(p)){
int treasuryStock = otherDataGatherer.treasuryStock();
int totalStock = otherDataGatherer.totalShares();
if(StockTransaction.STOCK_BUNDLE_SIZE + treasuryStock >= totalStock){
buyStock[playerId].setEnabled(false);
}
}
//Don't let the player buy stock if they cannot afford it.
if(stockPrices[playerId].currentPrice.getAmount() > highestAffordablePrice){
buyStock[playerId].setEnabled(false);
}
}
//Enable and disable bond actions.
int outstandingBonds = thisDataGatherer.getBonds();
repayBondAction.setEnabled(outstandingBonds > 0);
issueBondAction.setEnabled(outstandingBonds < 4);
}

endPrefixMapping

Class: jfreerails.server.parser.Track_TilesParser

Documentation

No documentation available

Source Code

public void endPrefixMapping(final java.lang.String prefix)
throws SAXException {
}

Called Methods

No outgoing method calls

start_ListOfTrackPieceTemplates

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* A container element start event handling method.
*
* @param meta
* attributes
*/

Source Code

/**
* A container element start event handling method.
*
* @param meta
* attributes
*/
void start_ListOfTrackPieceTemplates(final Attributes meta)
throws SAXException;

Called Methods

No outgoing method calls

removeFromArray

Class: jfreerails.util.ListXDDiffs

Documentation

No documentation available

Source Code

static int[] removeFromArray(int[] dim) {
int[] array = new int[dim.length - 1];
for (int i = 0; i < dim.length - 1; i++) {
array[i] = dim[i];
}
return array;
}

Called Methods

No outgoing method calls

reversePath

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public FreerailsPathIterator reversePath() {
int length = xpoints.size();
int[] reversed_xpoints = new int[length];
int[] reversed_ypoints = new int[length];
for (int i = 0; i < length; i++) {
reversed_xpoints[i] = xpoints.get(length - i - 1);
reversed_ypoints[i] = ypoints.get(length - i - 1);
}
return new SimplePathIteratorImpl(reversed_xpoints, reversed_ypoints);
}

getUpdatedTiles

Class: jfreerails.move.WorldDiffMove

Documentation

No documentation available

Source Code

public Rectangle getUpdatedTiles() {
return new Rectangle(x, y, w, h);
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.move.ChangeGameSpeedMove

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof ChangeGameSpeedMove))
return false;
final ChangeGameSpeedMove changeGameSpeedMove = (ChangeGameSpeedMove) o;
if (!newSpeed.equals(changeGameSpeedMove.newSpeed))
return false;
if (!oldSpeed.equals(changeGameSpeedMove.oldSpeed))
return false;
return true;
}

paintTile

Class: jfreerails.client.view.DetailMapRenderer

Documentation

No documentation available

Source Code

public void paintTile(Graphics g, int tileX, int tileY) {
background.paintTile(g, tileX, tileY);
trainsview.paint((Graphics2D) g);
stationRadius.paint((Graphics2D) g);
stationBoxes.paint((Graphics2D) g);
buildTrackRenderer.paint((Graphics2D) g);
}

MapViewJComponentConcrete

Class: jfreerails.client.view.MapViewJComponentConcrete

Documentation

No documentation available

Source Code

public MapViewJComponentConcrete() {
super();
MapViewJComponentMouseAdapter mva = new MapViewJComponentMouseAdapter();
this.addMouseListener(mva);
this.addMouseMotionListener(mva);
}

netWorth

Class: jfreerails.controller.StockPriceCalculator

Documentation

/** Returns the players networth at the start of this year.*/

Source Code

/** Returns the players networth at the start of this year.*/
long netWorth(int playerId){
FreerailsPrincipal pr = w.getPlayer(playerId).getPrincipal();
NetWorthCalculator nwc = new NetWorthCalculator(w, pr);
//Set the interval to beginning of time to start of this year.
GameCalendar calendar = (GameCalendar)w.get(ITEM.CALENDAR);
GameTime currentTime = w.currentTime();
int currentYear = calendar.getYear(currentTime.getTicks());
int ticksAtStartOfyear = calendar.getTicks(currentYear);
GameTime[] times = {GameTime.BIG_BANG, new GameTime(ticksAtStartOfyear + 1)};
nwc.setTimes(times);
return nwc.calculateValue().getAmount();
}

testChangingValues

Class: jfreerails.util.List1DDiffsTest

Documentation

No documentation available

Source Code

public void testChangingValues(){
list.add(String.valueOf(1));
assertEquals(diffs.get(0), String.valueOf(1));
assertEquals(diffs.size(), list.size());
diffs.set(String.valueOf(2), 0);
assertEquals(diffs.get(0), String.valueOf(2));
assertEquals(1, map.size());
diffs.set(String.valueOf(1),0);
assertEquals(0, map.size());
}

setProperty

Class: jfreerails.network.specifics.FreerailsClient

Documentation

No documentation available

Source Code

public void setProperty(ClientProperty propertyName, Serializable value) {
properties.put(propertyName.name(), value);
}

Called Methods

No outgoing method calls

BlankMapRenderer

Class: jfreerails.client.renderer.BlankMapRenderer

Documentation

No documentation available

Source Code

public BlankMapRenderer(float s) {
scale = s;
}

Called Methods

No outgoing method calls

getSpeed

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public double getSpeed() {
return speed;
}

Called Methods

No outgoing method calls

testBuildingStraight

Class: jfreerails.controller.TrackBuildingTest

Documentation

/** Tests building track from 5,5 to 10,5 */

Source Code

/** Tests building track from 5,5 to 10,5 */
public void testBuildingStraight() {
ImPoint from = new ImPoint(5, 5);
ImPoint to = new ImPoint(10, 5);
try {
// Check there is no track before we build it.
for (int x = 5; x <= 10; x++) {
TrackPiece tp = ((FreerailsTile) w.getTile(x, 5)).getTrackPiece();
assertEquals(NullTrackType.NULL_TRACK_TYPE_RULE_NUMBER, tp
.getTrackTypeID());
}
pathFinder.setupSearch(from, to, bts);
pathFinder.search(-1);
assertEquals(pathFinder.getStatus(),
IncrementalPathFinder.PATH_FOUND);
Step[] path = pathFinder.pathAsVectors();
assertEquals(path.length, 5);
for (int i = 0; i < 5; i++) {
assertEquals(Step.EAST, path[i]);
}
MoveStatus ms = producer.buildTrack(from, path);
assertTrue(ms.message, ms.ok);
// Check track has been built.
for (int x = 5; x <= 10; x++) {
TrackPiece tp = ((FreerailsTile) w.getTile(x, 5)).getTrackPiece();
assertEquals(0, tp.getTrackTypeID());
}
} catch (PathNotFoundException e) {
fail();
}
}

propertyChange

Class: jfreerails.client.view.RHSJTabPane

Documentation

/**
* Updates the Terrain Info Panel if the specified PropertyChangeEvent was
* triggered by the cursor moving.
*/

Source Code

/**
* Updates the Terrain Info Panel if the specified PropertyChangeEvent was
* triggered by the cursor moving.
*/
public void propertyChange(ModelRoot.Property prop, Object before,
Object after) {
if (prop.equals(ModelRoot.Property.CURSOR_POSITION)) {
ImPoint p = (ImPoint) after;
terrainInfoPanel.setTerrainType(((FreerailsTile) world.getTile(p.x,
p.y)).getTerrainTypeID());
}
}

readResolve

Class: jfreerails.world.top.SKEY

Documentation

No documentation available

Source Code

private Object readResolve() throws ObjectStreamException {
return keys[this.keyNumber];
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.util.Pair

Documentation

No documentation available

Source Code

public String toString() {
return "(" + e1.toString() + ", " + e2.toString() + ")";
}

Called Methods

No outgoing method calls

OpenListEntry

Class: jfreerails.controller.OpenListEntry

Documentation

No documentation available

Source Code

OpenListEntry(int _f, int _node) {
this.f = _f;
this.node = _node;
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.world.accounts.Bill

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof Bill) {
Bill test = (Bill) o;
return test.amount.equals(amount) && category == test.category;
}
return false;
}

logon

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public LogOnResponse logon(LogOnRequest lor) {
NameAndPassword p = new NameAndPassword(lor.getUsername(), lor
.getPassword());
boolean isReturningPlayer = isPlayer(lor.getUsername());
if (!this.newPlayersAllowed && !isReturningPlayer) {
return LogOnResponse.rejected("New logins not allowed.");
}
if (currentlyLoggedOn.contains(p)) {
return LogOnResponse.rejected("Already logged on.");
}
if (isReturningPlayer) {
if (!players.contains(p)) {
return LogOnResponse.rejected("Incorrect password.");
}
} else {
players.add(p);
}
currentlyLoggedOn.add(p);
return LogOnResponse.accepted(players.indexOf(p));
}

setPathToReadFrom

Class: jfreerails.client.common.ImageManagerImpl

Documentation

No documentation available

Source Code

public void setPathToReadFrom(String s) {
pathToReadFrom = s;
}

Called Methods

No outgoing method calls

Stats

Class: jfreerails.controller.Stats

Documentation

No documentation available

Source Code

public Stats(ReadOnlyWorld w, FreerailsPrincipal principal, final GameTime[] totalTimeInterval){
TransactionAggregator operatingFundsAggregator = new TransactionAggregator(w,
principal) {
@Override
protected boolean condition(int i) {
int transactionTicks = w.getTransactionTimeStamp(
principal, i).getTicks();
int from = totalTimeInterval[0].getTicks();
int to = totalTimeInterval[1].getTicks();
return transactionTicks >= from && transactionTicks <=to;
}
};
operatingFunds= operatingFundsAggregator.calculateValue();
track = calTrackTotal(TRACK, w, principal, totalTimeInterval[0]);
ItemsTransactionAggregator aggregator = new ItemsTransactionAggregator(
w, principal);
aggregator.setTimes(totalTimeInterval);
aggregator.setCategory(STATIONS);
stations = aggregator.calculateValue();
aggregator.setCategory(TRAIN);
rollingStock = aggregator.calculateValue();
aggregator.setCategory(INDUSTRIES);
industries = aggregator.calculateValue();
aggregator.setCategory(BOND);
loans = aggregator.calculateValue();
aggregator.setCategory(ISSUE_STOCK);
equity= aggregator.calculateValue();
//If we don't initialize this variable
//we get a NPE when we don't own any stock in others RRs
otherRrStock = new Money(0);
int thisPlayerId = w.getID(principal);
StockPrice[] stockPrices = (new StockPriceCalculator(w)).calculate();
for (int playerId = 0; playerId < w.getNumberOfPlayers(); playerId++) {
aggregator.setCategory(TRANSFER_STOCK);
aggregator.setType(thisPlayerId);
int quantity = aggregator.calculateQuantity();
if (playerId == thisPlayerId) {
treasuryStock = new Money(quantity
* stockPrices[playerId].currentPrice.getAmount());
} else {
otherRrStock = new Money(quantity
* stockPrices[playerId].currentPrice.getAmount()
+ otherRrStock.getAmount());
}
}
calProfit();
}

sendListUpdated

Class: jfreerails.network.specifics.MoveChainFork

Documentation

No documentation available

Source Code

private void sendListUpdated(KEY key, int index, FreerailsPrincipal p) {
for (int i = 0; i < listListeners.size(); i++) {
WorldListListener l = listListeners.get(i);
l.listUpdated(key, index, p);
}
}

showSaveGame

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showSaveGame(){
SaveGameJPanel saveGameJPanel = new SaveGameJPanel();
saveGameJPanel.setup(modelRoot, vl, this.closeCurrentDialogue);
showContent(saveGameJPanel);
}

update

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

/**
* Updates the game model, then reads and deals with the outstanding
* messages from each of the connected clients. This method is synchronized
* to prevent moves being sent out while addConnection(.) is executing.
*/

Source Code

/**
* Updates the game model, then reads and deals with the outstanding
* messages from each of the connected clients. This method is synchronized
* to prevent moves being sent out while addConnection(.) is executing.
*/
public synchronized void update() {
if (null != serverGameModel) {
serverGameModel.update();
}
try {
Iterator<NameAndPassword> it = acceptedConnections.keySet()
.iterator();
while (it.hasNext()) {
NameAndPassword player = it.next();
Connection2Client connection = acceptedConnections.get(player);
if (connection.isOpen()) {
FreerailsSerializable[] messages = connection
.readFromClient();
for (int i = 0; i < messages.length; i++) {
if (messages[i] instanceof Message2Server) {
Message2Server message2 = (Message2Server) messages[i];
MessageStatus cStatus = message2.execute(this);
logger.fine(message2.toString());
connection.writeToClient(cStatus);
} else if (messages[i] instanceof MessageStatus) {
MessageStatus messageStatus = (MessageStatus) messages[i];
if (messageStatus.getId() == this.confirmationID) {
/*
* The client is confirming that they have
* updated their world object to the current
* version.
*/
this.confirmedPlayers.add(player);
logger.fine("Confirmed player " + player);
}
logger.fine(messages[i].toString());
} else if (messages[i] instanceof Move
|| messages[i] instanceof PreMove) {
Player player2 = getWorld().getPlayer(
players.indexOf(player));
FreerailsPrincipal principal = player2
.getPrincipal();
Move move;
boolean isMove = messages[i] instanceof Move;
if (isMove) {
move = (Move) messages[i];
} else {
PreMove pm = (PreMove) messages[i];
move = pm.generateMove(getWorld());
}
MoveStatus mStatus = move.tryDoMove(
this.getWorld(), principal);
if (mStatus.isOk()) {
move.doMove(getWorld(), principal);
/*
* We don't send the move to the client that
* submitted it.
*/
send2AllExcept(connection, move);
}
if (isMove) {
connection.writeToClient(mStatus);
} else {
connection.writeToClient(PreMoveStatus
.fromMoveStatus(mStatus));
}
} else {
logger.fine(messages[i].toString());
}
}
connection.flush();
} else {
/* Remove connection. */
this.removeConnection(player);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

generateMove

Class: jfreerails.move.AddPlayerMove

Documentation

No documentation available

Source Code

public static AddPlayerMove generateMove(ReadOnlyWorld w, Player player) {
/**
* create a new player with a corresponding Principal
*/
Player player2add = new Player(player.getName(), w.getNumberOfPlayers());
return new AddPlayerMove(player2add);
}

canRemoveFromHead

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public boolean canRemoveFromHead(TrainPositionOnMap b) {
if (headsAreEqual(this, b)) {
FreerailsPathIterator path = b.path();
int i = 0;
IntLine line = new IntLine();
while (path.hasNext()) {
path.nextSegment(line);
if (this.getX(i) != line.x1 || this.getY(i) != line.y1) {
return false;
}
i++;
}
return true;
}
return false;
}

RandomPathFinder

Class: jfreerails.controller.RandomPathFinder

Documentation

No documentation available

Source Code

public RandomPathFinder(FlatTrackExplorer tx) {
trackExplorer = tx;
}

Called Methods

No outgoing method calls

showSelectWagons

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showSelectWagons() {
selectWagons.resetSelectedWagons();
selectWagons.setEngineType(selectEngine.getEngineType());
showContent(selectWagons);
}

nextActivity

Class: jfreerails.world.common.ActivityIterator

Documentation

No documentation available

Source Code

void nextActivity() throws NoSuchElementException;

Called Methods

No outgoing method calls

noChangeJMenuItemActionPerformed

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void noChangeJMenuItemActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_noChangeJMenuItemActionPerformed
noChange();
}// GEN-LAST:event_noChangeJMenuItemActionPerformed

newMap

Class: jfreerails.network.specifics.SavedGamesManager4UnitTests

Documentation

No documentation available

Source Code

public Serializable newMap(String name) throws IOException {
return new WorldImpl(10, 10);
}

Called Methods

No outgoing method calls

get

Class: jfreerails.util.List3DDiff

Documentation

No documentation available

Source Code

public List<T> get(int d1, int d2) {
List<T> list = new ArrayList<T>();
for(int d3 = 0; d3 < sizeD3(d1, d2); d3++) {
list.add(get(d1, d2, d3));
}
return list;
}

showTrainList

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showTrainList() {
if (world.size(modelRoot.getPrincipal(), KEY.TRAINS) > 0) {
final TrainListJPanel trainList = new TrainListJPanel();
trainList.setup(modelRoot, vl, closeCurrentDialogue);
trainList.setShowTrainDetailsActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int id = trainList.getSelectedTrainID();
showTrainOrders(id);
}
});
showContent(trainList);
} else {
modelRoot.setProperty(Property.QUICK_MESSAGE, "There are"
+ " no trains to display!");
}
}

paint

Class: jfreerails.client.view.SelectWagonsJPanel

Documentation

No documentation available

Source Code

@Override
public void paint(Graphics g) {
// paint the background
g.drawImage(this.stationView, 0, 0, null);
int x = this.getWidth();
int y = 330;
final int SCALED_IMAGE_HEIGHT = 50;
// paint the wagons
for (int i = this.wagons.size() - 1; i >= 0; i--) { // Count down so we
// paint the wagon
// at the end of the
// train first.
Integer type = wagons.get(i);
Image image = rr.getWagonImages(type.intValue()).getSideOnImage();
int scaledWidth = image.getWidth(null) * SCALED_IMAGE_HEIGHT
/ image.getHeight(null);
x -= scaledWidth;
g.drawImage(image, x, y, scaledWidth, SCALED_IMAGE_HEIGHT, null);
}
// paint the engine
if (-1 != this.engineType) { // If an engine is selected.
Image image = rr.getEngineImages(engineType).getSideOnImage();
int scaledWidth = (image.getWidth(null) * SCALED_IMAGE_HEIGHT)
/ image.getHeight(null);
x -= scaledWidth;
g.drawImage(image, x, y, scaledWidth, SCALED_IMAGE_HEIGHT, null);
}
this.paintChildren(g);
}

calcV

Class: jfreerails.world.train.SpeedAgainstTime

Documentation

/**
* @throws IllegalArgumentException
* iff t < 0 or t > getT()
*/

Source Code

/**
* @throws IllegalArgumentException
* iff t < 0 or t > getT()
*/
double calcV(double t);

Called Methods

No outgoing method calls

SetWorldMessage2Client

Class: jfreerails.network.specifics.SetWorldMessage2Client

Documentation

/**
* Note, makes a defensive copy of the world object passed to it.
*/

Source Code

/**
* Note, makes a defensive copy of the world object passed to it.
*/
public SetWorldMessage2Client(int id, World world) {
this.id = id;
this.world = world.defensiveCopy();
}

getElementAt

Class: jfreerails.client.view.TrainOrdersListModel

Documentation

No documentation available

Source Code

public Object getElementAt(int index) {
Schedule s = getSchedule();
int gotoStatus;
if (s.getNextScheduledOrder() == index) {
if (s.hasPriorityOrders()) {
gotoStatus = GOTO_AFTER_PRIORITY_ORDERS;
} else {
gotoStatus = GOTO_NOW;
}
} else {
if (s.hasPriorityOrders() && 0 == index) {
// These orders are the priority orders.
gotoStatus = GOTO_NOW;
} else {
gotoStatus = DONT_GOTO;
}
}
boolean isPriorityOrders = 0 == index && s.hasPriorityOrders();
TrainOrdersModel order = getSchedule().getOrder(index);
return new TrainOrdersListElement(isPriorityOrders, gotoStatus, order,
trainNumber);
}

testSetupSearch

Class: jfreerails.controller.PathOnTrackFinderTest

Documentation

No documentation available

Source Code

public void testSetupSearch() {
Step[] path = { EAST, EAST, SOUTH_EAST };
ImPoint start = new ImPoint(5, 5);
ImPoint end = Step.move(start, path);
producer.buildTrack(start, path);
try {
pathFinder.setupSearch(start, end);
} catch (PathNotFoundException e) {
fail("Track at both of the points so no exception should be thrown");
}
try {
pathFinder.setupSearch(start, new ImPoint(10, 10));
fail("No track at one of the points so an exception should be thrown");
} catch (PathNotFoundException e) {
}
try {
pathFinder.setupSearch(new ImPoint(10, 10), end);
fail("No track at one of the points so an exception should be thrown");
} catch (PathNotFoundException e) {
}
}

createCashJLabel

Class: experimental.SimpleComponentFactoryImpl2

Documentation

No documentation available

Source Code

public JLabel createCashJLabel() {
return null;
}

Called Methods

No outgoing method calls

getID

Class: jfreerails.controller.Message2Client

Documentation

/** Returns the id of this command. */

Source Code

/** Returns the id of this command. */
int getID();

Called Methods

No outgoing method calls

tearDown

Class: jfreerails.network.AbstractEchoGameServerTestCase

Documentation

No documentation available

Source Code

@Override
protected synchronized void tearDown() throws Exception {
server.stop();
}

uGet

Class: jfreerails.util.List1DDiff

Documentation

No documentation available

Source Code

@Override
T uGet(int... i) {
if (i.length != 1)
throw new IllegalArgumentException();
return underlyingList.get(i[0]);
}

getKeyID

Class: jfreerails.world.top.KEY

Documentation

No documentation available

Source Code

int getKeyID() {
return keyNumber;
}

Called Methods

No outgoing method calls

removeLastD2

Class: jfreerails.util.List3DImpl

Documentation

No documentation available

Source Code

public void removeLastD2(int d1) {
ArrayList<ArrayList<T>> dim2 = elementData.get(d1);
int last = dim2.size()-1;
ArrayList<T> dim3 = dim2.get(last);
if(dim3.size() > 0)
throw new IllegalStateException(String.valueOf(d1));
dim2.remove(last);
}

Called Methods

No outgoing method calls

testMove

Class: jfreerails.move.AddTransactionMoveTest

Documentation

No documentation available

Source Code

@Override
public void testMove() {
Money currentBalance = getWorld().getCurrentBalance(
MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(new Money(0), currentBalance);
Transaction t = new Receipt(new Money(100),
Transaction.Category.MISC_INCOME);
Move m = new AddTransactionMove(MapFixtureFactory.TEST_PRINCIPAL, t);
assertTryMoveIsOk(m);
assertTryUndoMoveFails(m);
assertDoMoveIsOk(m);
currentBalance = getWorld().getCurrentBalance(
MapFixtureFactory.TEST_PRINCIPAL);
assertEquals(new Money(100), currentBalance);
final Player PLAYER_WITHOUT_ACCOUNT = new Player(
"PLAYER_WITHOUT_ACCOUNT", 4);
assertSurvivesSerialisation(m);
Move m2 = new AddTransactionMove(PLAYER_WITHOUT_ACCOUNT.getPrincipal(),
t);
assertTryMoveFails(m2);
assertOkAndRepeatable(m);
}

ServerGameModelImpl

Class: jfreerails.server.ServerGameModelImpl

Documentation

No documentation available

Source Code

public ServerGameModelImpl() {
this(null, new Vector<ServerAutomaton>());
}

getInstance

Class: jfreerails.world.common.Step

Documentation

No documentation available

Source Code

public static Step getInstance(int dx, int dy) {
if ((((dx < -1) || (dx > 1)) || ((dy < -1) || (dy > 1)))
|| ((dx == 0) && (dy == 0))) {
throw new IllegalArgumentException(
dx
+ " and "
+ dy
+ ": The values passed both must be integers in the range -1 to 1, and not both equal 0.");
}
return vectors[dx + 1][dy + 1];
}

Called Methods

No outgoing method calls

testGetLength

Class: jfreerails.world.track.TrackConfigurationTest

Documentation

No documentation available

Source Code

public void testGetLength() {
TrackConfiguration a = TrackConfiguration.getFlatInstance("010010000");
TrackConfiguration b = TrackConfiguration.getFlatInstance("010010010");
assertEquals(30, a.getLength());
assertEquals(60, b.getLength());
}

getTileViewWithNumber

Class: jfreerails.client.renderer.MyRenderersRoot

Documentation

No documentation available

Source Code

@Override
public TileRenderer getTileViewWithNumber(int i) {
throw new UnsupportedOperationException("Not supported yet.");
}

Called Methods

No outgoing method calls

InterestChargeMoveGenerator

Class: jfreerails.server.InterestChargeMoveGenerator

Documentation

No documentation available

Source Code

public InterestChargeMoveGenerator(MoveReceiver mr) {
this.moveReceiver = mr;
}

Called Methods

No outgoing method calls

parse

Class: jfreerails.server.parser.Track_TilesParser

Documentation

No documentation available

Source Code

private static void parse(final InputSource input,
final Track_TilesParser recognizer) throws SAXException,
ParserConfigurationException, IOException {
javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory
.newInstance();
factory.setValidating(true); // the code was generated according DTD
factory.setNamespaceAware(false); // the code was generated according
// DTD
org.xml.sax.XMLReader parser = factory.newSAXParser().getXMLReader();
parser.setContentHandler(recognizer);
parser.setErrorHandler(recognizer.getDefaultErrorHandler());
parser.parse(input);
}

setIcon

Class: experimental.TrackRenderer

Documentation

No documentation available

Source Code

void setIcon(String typeName) {
try {
String relativeFileName = "icons" + File.separator + typeName
+ ".png";
relativeFileName = relativeFileName.replace(' ', '_');
Image im = imageManager.getImage(relativeFileName);
icon = im;
} catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException(e);
}
}

canStepForward

Class: jfreerails.world.train.PathWalker

Documentation

/**
* Returns true if we have not reached the end of the path.
*/

Source Code

/**
* Returns true if we have not reached the end of the path.
*/
boolean canStepForward();

Called Methods

No outgoing method calls

addTypesToWorld

Class: jfreerails.world.top.WagonAndEngineTypesFactory

Documentation

No documentation available

Source Code

public void addTypesToWorld(World w) {
// Wagon types
WagonType[] wagonTypes = new WagonType[] {
new WagonType("Mail", WagonType.MAIL),
new WagonType("Passengers", WagonType.PASSENGER),
new WagonType("Livestock", WagonType.FAST_FREIGHT),
new WagonType("Coffee", WagonType.SLOW_FREIGHT),
new WagonType("Wood", WagonType.BULK_FREIGHT), };
for (int i = 0; i < wagonTypes.length; i++) {
w.add(SKEY.WAGON_TYPES, wagonTypes[i]);
}
// Engine types
EngineType[] engineTypes = new EngineType[] {
new EngineType("Grasshopper", 1000, new Money(10000), 10,
new Money(100)),
new EngineType("Norris", 1000, new Money(10000), 15, new Money(
100)), };
for (int i = 0; i < engineTypes.length; i++) {
w.add(SKEY.ENGINE_TYPES, engineTypes[i]);
}
}

getAmount

Class: jfreerails.world.cargo.ImmutableCargoBundle

Documentation

No documentation available

Source Code

public int getAmount(CargoBatch cb) {
int amount = 0;
for (int i = 0; i < batches.size(); i++) {
if (batches.get(i).equals(cb)) {
amount += amounts.get(i);
}
}
return amount;
}

generateMove

Class: jfreerails.controller.AddStationPreMove

Documentation

No documentation available

Source Code

public Move generateMove(ReadOnlyWorld world) {
TrackMoveTransactionsGenerator transactionsGenerator = new TrackMoveTransactionsGenerator(
world, principal);
FreerailsTile oldTile = (FreerailsTile) world.getTile(p.x, p.y);
String cityName;
String stationName;
FreerailsTile ft = (FreerailsTile)world.getTile(p.x, p.y);
TrackPiece before = ft.getTrackPiece();
TrackRule trackRule = (TrackRule) world.get(SKEY.TRACK_RULES,
this.ruleNumber);
int owner = ChangeTrackPieceCompositeMove.getOwner(principal, world);
TrackPiece after = new TrackPieceImpl(before.getTrackConfiguration(),
trackRule, owner, ruleNumber);
ChangeTrackPieceMove upgradeTrackMove = new ChangeTrackPieceMove(
before, after, p);
CompositeMove move;
if (!oldTile.getTrackPiece().getTrackRule().isStation()) {
// There isn't already a station here, we need to pick a name and
// add an entry
// to the station list.
CalcNearestCity cNC = new CalcNearestCity(world, p.x, p.y);
try {
cityName = cNC.findNearestCity();
VerifyStationName vSN = new VerifyStationName(world, cityName);
stationName = vSN.getName();
} catch (NoSuchElementException e) {
// there are no cities, this should never happen during a proper
// game. However
// some of the unit tests create stations when there are no
// cities.
stationName = "Central Station #"
+ world.size(principal, KEY.STATIONS);
}
// check the terrain to see if we can build a station on it...
move = AddStationMove.generateMove(world, stationName, p,
upgradeTrackMove, principal);
move = addSupplyAndDemand(move, world);
move = transactionsGenerator.addTransactions(move);
} else {
// Upgrade an existing station.
move = AddStationMove.upgradeStation(upgradeTrackMove);
}
return move;
}

startElement

Class: jfreerails.server.parser.CargoAndTerrainParser

Documentation

/**
* This SAX interface method is implemented by the parser.
*
*/

Source Code

/**
* This SAX interface method is implemented by the parser.
*
*/
public final void startElement(java.lang.String ns, java.lang.String name,
java.lang.String qname, Attributes attrs) throws SAXException {
dispatch(true);
context.push(new Object[] { qname,
new org.xml.sax.helpers.AttributesImpl(attrs) });
if ("Converts".equals(name)) {
handler.handle_Converts(attrs);
} else if ("Tile".equals(name)) {
handler.start_Tile(attrs);
} else if ("Cargo".equals(name)) {
handler.handle_Cargo(attrs);
} else if ("Cargo_Types".equals(name)) {
handler.start_Cargo_Types(attrs);
} else if ("Terrain_Types".equals(name)) {
handler.start_Terrain_Types(attrs);
} else if ("Types".equals(name)) {
handler.start_Types(attrs);
} else if ("Consumes".equals(name)) {
handler.handle_Consumes(attrs);
} else if ("Produces".equals(name)) {
handler.handle_Produces(attrs);
}
}

GameSpeed

Class: jfreerails.world.common.GameSpeed

Documentation

No documentation available

Source Code

public GameSpeed(int speed) {
this.speed = speed;
}

Called Methods

No outgoing method calls

getTerrainTypeID

Class: jfreerails.world.terrain.TerrainTile

Documentation

No documentation available

Source Code

int getTerrainTypeID();

Called Methods

No outgoing method calls

TrainPositionOnMap

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public TrainPositionOnMap(ImInts xs, ImInts ys) {
this.xpoints = xs;
this.ypoints = ys;
this.acceleration = 0d;
this.speed = 0d;
this.activity = SpeedTimeAndStatus.TrainActivity.READY;
}

Called Methods

No outgoing method calls

getNumberOfWagons

Class: jfreerails.world.train.TrainModel

Documentation

No documentation available

Source Code

public int getNumberOfWagons() {
return wagonTypes.size();
}

TrainOrdersListModel

Class: jfreerails.client.view.TrainOrdersListModel

Documentation

No documentation available

Source Code

public TrainOrdersListModel(ReadOnlyWorld w, int trainNumber,
FreerailsPrincipal p) {
this.trainNumber = trainNumber;
this.w = w;
this.principal = p;
assert (null != getSchedule());
}

getType

Class: jfreerails.util.ListKey

Documentation

No documentation available

Source Code

public Type getType() {
return type;
}

Called Methods

No outgoing method calls

listDiffs

Class: jfreerails.move.WorldDiffMove

Documentation

No documentation available

Source Code

public int listDiffs() {
return listChanges.size();
}

upgradeStation

Class: jfreerails.move.AddStationMove

Documentation

No documentation available

Source Code

public static AddStationMove upgradeStation(
ChangeTrackPieceMove upgradeTrackMove) {
return new AddStationMove(new Move[] { upgradeTrackMove });
}

Called Methods

No outgoing method calls

getTypeName

Class: jfreerails.world.track.TrackRuleProperties

Documentation

No documentation available

Source Code

public String getTypeName() {
return typeName;
}

Called Methods

No outgoing method calls

toString

Class: jfreerails.move.TimeTickMove

Documentation

No documentation available

Source Code

@Override
public String toString() {
return "TimeTickMove: " + oldTime + "=>" + newTime;
}

Called Methods

No outgoing method calls

get

Class: jfreerails.util.List2DDiff

Documentation

No documentation available

Source Code

public T get(int d1, int d2) {
return super.get(d1, d2);
}

contentsRestored

Class: jfreerails.controller.ScreenHandler

Documentation

No documentation available

Source Code

public boolean contentsRestored() {
return bufferStrategy.contentsRestored();
}

Called Methods

No outgoing method calls

saveGame

Class: jfreerails.network.specifics.SavedGamesManager

Documentation

No documentation available

Source Code

void saveGame(Serializable w, String s) throws IOException;

Called Methods

No outgoing method calls

doMove

Class: jfreerails.controller.MoveExecutor

Documentation

No documentation available

Source Code

MoveStatus doMove(Move m);

Called Methods

No outgoing method calls

jList1ValueChanged

Class: jfreerails.client.view.LoadGameJPanel

Documentation

No documentation available

Source Code

private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged
okButton.setEnabled(jList1.getSelectedIndex() != -1);
}//GEN-LAST:event_jList1ValueChanged

Called Methods

No outgoing method calls

initComponents

Class: jfreerails.client.common.MyGlassPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the FormEditor.
*/
private void initComponents() { // GEN-BEGIN:initComponents
contentPanel = new javax.swing.JPanel();
setLayout(new java.awt.GridBagLayout());
java.awt.GridBagConstraints gridBagConstraints1;
setOpaque(false);
addKeyListener(new java.awt.event.KeyAdapter() {
@Override
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mousePressed(java.awt.event.MouseEvent evt) {
formMousePressed(evt);
}
});
addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
@Override
public void mouseMoved(java.awt.event.MouseEvent evt) {
formMouseMoved(evt);
}
});
contentPanel.setPreferredSize(new java.awt.Dimension(60, 40));
contentPanel.setMinimumSize(new java.awt.Dimension(60, 40));
contentPanel.setBackground(java.awt.Color.red);
contentPanel.setMaximumSize(new java.awt.Dimension(60, 40));
gridBagConstraints1 = new java.awt.GridBagConstraints();
gridBagConstraints1.gridx = 2;
gridBagConstraints1.gridy = 1;
add(contentPanel, gridBagConstraints1);
}

fromServer

Class: jfreerails.network.specifics.MovePrecommitter

Documentation

No documentation available

Source Code

void fromServer(PreMoveStatus pms) {
rollBackPrecommittedMoves();
PreMove pm = (PreMove) uncomitted.removeFirst();
if (pms.ms.ok) {
logger.finest("PreMove accepted by server: " + pms.toString());
Move m = pm.generateMove(w);
MoveStatus ms = m.doMove(w, Player.AUTHORITATIVE);
if (!ms.ok) {
throw new IllegalStateException();
}
} else {
logger.info("PreMove rejected by server: " + pms.ms.message);
}
precommitMoves();
}

addOrder

Class: jfreerails.world.train.MutableSchedule

Documentation

/**
* Inserts an order at the specified position. Note you must call
* setPriorityOrders() to set the priority orders.
*/

Source Code

/**
* Inserts an order at the specified position. Note you must call
* setPriorityOrders() to set the priority orders.
*/
public void addOrder(int orderNumber, TrainOrdersModel order) {
orders.add(orderNumber, order);
if (nextScheduledOrder >= orderNumber) {
nextScheduledOrder++;
}
if (-1 == nextScheduledOrder && 0 < numberOfScheduledStops()) {
nextScheduledOrder = firstScheduleStop();
}
}

append

Class: jfreerails.world.common.ImInts

Documentation

No documentation available

Source Code

public ImInts append(int... extra) {
int[] newInts = new int[ints.length + extra.length];
System.arraycopy(ints, 0, newInts, 0, ints.length);
System.arraycopy(extra, 0, newInts, ints.length, extra.length);
return new ImInts(newInts);
}

Called Methods

No outgoing method calls

getOrder

Class: jfreerails.world.train.Schedule

Documentation

No documentation available

Source Code

TrainOrdersModel getOrder(int i);

Called Methods

No outgoing method calls

initComponents

Class: jfreerails.client.view.TerrainInfoJPanel

Documentation

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/

Source Code

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void initComponents() {// GEN-BEGIN:initComponents
java.awt.GridBagConstraints gridBagConstraints;
terrainImage = new javax.swing.JLabel();
terrainName = new javax.swing.JLabel();
terrainDescription = new javax.swing.JLabel();
setLayout(new java.awt.GridBagLayout());
terrainImage.setIcon(new javax.swing.ImageIcon(getClass().getResource(
"/jfreerails/client/graphics/terrain/City_0.png")));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.insets = new java.awt.Insets(8, 8, 4, 4);
add(terrainImage, gridBagConstraints);
terrainName.setFont(new java.awt.Font("Dialog", 1, 14));
terrainName.setText("City");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 8);
add(terrainName, gridBagConstraints);
terrainDescription.setFont(new java.awt.Font("Dialog", 0, 12));
terrainDescription
.setText("<html>\n<p>Right-of-Way costs X per mile. </p>\n<table width=\"75%\" >\n <tr> \n <td><strong>Supplies:</strong></td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td>Mail </td>\n <td>2</td>\n </tr>\n <tr> \n <td>Passengers</td>\n <td>2</td>\n </tr>\n <tr> \n <td> <strong>Demands</strong></td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td>Mail</td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td>Passengers</td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td><strong>Converts</strong></td>\n <td>&nbsp;</td>\n </tr>\n <tr> \n <td>Livestock to Food</td>\n <td>&nbsp;</td>\n </tr>\n <tr>\n <td>Steel to Goods</td>\n <td>&nbsp;</td>\n </tr>\n</table>\n</html>");
terrainDescription.setVerticalAlignment(javax.swing.SwingConstants.TOP);
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new java.awt.Insets(4, 8, 4, 8);
add(terrainDescription, gridBagConstraints);
}// GEN-END:initComponents

Called Methods

No outgoing method calls

set

Class: jfreerails.util.ListXDDiffs

Documentation

No documentation available

Source Code

public void set(T element, int... i) {
// Check bounds..
checkBounds(i);
int last = i[i.length - 1];
int[] dim = checkBounds(i);
ListKey elementKey = new ListKey(ListKey.Type.Element, listID, i);
boolean b = getUnderlyingSize(dim) > last;
if (b && Utils.equal(uGet(i), element)) {
if (diffs.containsKey(elementKey))
diffs.remove(elementKey);
} else {
diffs.put(elementKey, element);
}
}

refreshSavedGames

Class: jfreerails.network.specifics.FreerailsGameServer

Documentation

No documentation available

Source Code

public void refreshSavedGames() {
Message2Client setMaps = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.MAPS_AVAILABLE,
new ImStringList(savedGamesManager.getNewMapNames()));
ImStringList savedGameNames = new ImStringList(
savedGamesManager.getSaveGameNames());
Message2Client setSaveGames = new SetPropertyMessage2Client(
getNextClientCommandId(),
ClientControlInterface.ClientProperty.SAVED_GAMES, savedGameNames);
send2All(setMaps);
send2All(setSaveGames);
}

getLegalRoutes

Class: jfreerails.world.track.TrackRule

Documentation

No documentation available

Source Code

Step[] getLegalRoutes(Step directionComingFrom);

Called Methods

No outgoing method calls

getRGB

Class: jfreerails.world.terrain.TileTypeImpl

Documentation

/**
* @return The RGB value mapped to this terrain type.
*/

Source Code

/**
* @return The RGB value mapped to this terrain type.
*/
public int getRGB() {
return rgb;
}

Called Methods

No outgoing method calls

getBuildTrackController

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

public BuildTrackController getBuildTrackController() {
return mainMap.getBuildTrackController();
}

testStops1

Class: jfreerails.controller.MoveTrainPreMove2ndTest

Documentation

/** Test that when the train arrives at a non station tile it keeps moving. */

Source Code

/** Test that when the train arrives at a non station tile it keeps moving. */
public void testStops1() {
for (int i = 0; i < 5; i++) {
TrainMotion tm = moveTrain();
PositionOnTrack pot = tm.getFinalPosition();
assertEquals(14 + i, pot.getX());
assertEquals(READY, tm.getActivity());
assertTrue(tm.getSpeedAtEnd() > 0);
}
}

compareTo

Class: jfreerails.controller.WagonLoad

Documentation

No documentation available

Source Code

public int compareTo(WagonLoad test) {
return quantity - test.quantity;
}

Called Methods

No outgoing method calls

tryUndoMove

Class: jfreerails.move.NextActivityMove

Documentation

No documentation available

Source Code

public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
ActivityIterator ai = w.getActivities(principal, index);
ai.gotoLastActivity();
Activity act = ai.getActivity();
if (act.equals(activity))
return MoveStatus.MOVE_OK;
return MoveStatus.moveFailed("Expected " + activity + " but found "
+ act);
}

setupStockMenu

Class: jfreerails.client.view.BrokerScreenHtmlJFrame

Documentation

No documentation available

Source Code

private void setupStockMenu(){
stocks.removeAll();
ReadOnlyWorld world = modelRoot.getWorld();
int thisPlayerId = world.getID(modelRoot.getPrincipal());
int numberOfPlayers = world.getNumberOfPlayers();
buyStock = new Action[numberOfPlayers];
sellStock = new Action[numberOfPlayers];
for(int playerId = 0 ; playerId < numberOfPlayers; playerId++){
final boolean isThisPlayer = playerId == thisPlayerId;
final int otherPlayerId = playerId;
Player otherPlayer = world.getPlayer(playerId);
String playerLabel = isThisPlayer ? "Treasury stock" : otherPlayer.getName();
String buyLabel = "Buy 10,000 shares of " + playerLabel;
String sellLabel = "Sell 10,000 shares of " + playerLabel;
buyStock[playerId] = new AbstractAction(buyLabel) {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
StockPrice stockPrice = new StockPriceCalculator(modelRoot.getWorld()).calculate()[otherPlayerId];
Money sharePrice = isThisPlayer ? stockPrice.treasuryBuyPrice : stockPrice.buyPrice;
StockTransaction t = StockTransaction
.buyOrSellStock(otherPlayerId, StockTransaction.STOCK_BUNDLE_SIZE, sharePrice);
Move move = new AddTransactionMove(modelRoot.getPrincipal(), t);
modelRoot.doMove(move);
updateHtml();
}
};
sellStock[playerId] = new AbstractAction(sellLabel) {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
StockPrice stockPrice = new StockPriceCalculator(modelRoot.getWorld()).calculate()[otherPlayerId];
Money sharePrice = isThisPlayer ? stockPrice.treasurySellPrice : stockPrice.sellPrice;
StockTransaction t = StockTransaction
.buyOrSellStock(otherPlayerId, -StockTransaction.STOCK_BUNDLE_SIZE, sharePrice);
Move move = new AddTransactionMove(modelRoot.getPrincipal(), t);
modelRoot.doMove(move);
updateHtml();
}
};
stocks.add(buyStock[playerId]);
stocks.add(sellStock[playerId]);
}
enableAndDisableActions();
}

main

Class: jfreerails.world.track.TrackConfigurationTest

Documentation

No documentation available

Source Code

public static void main(java.lang.String[] args) {
junit.textui.TestRunner.run(suite());
}

paintTile

Class: jfreerails.client.view.MapViewJComponentConcrete

Documentation

No documentation available

Source Code

public void paintTile(Graphics g, int tileX, int tileY) {
throw new UnsupportedOperationException();
}

Called Methods

No outgoing method calls

tryUndoMove

Class: jfreerails.move.AddTransactionMove

Documentation

No documentation available

Source Code

public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int size = w.getNumberOfTransactions(this.principal);
if (0 == size) {
return MoveStatus.moveFailed("No transactions to remove!");
}
Transaction lastTransaction = w
.getTransaction(this.principal, size - 1);
if (lastTransaction.equals(this.transaction)) {
return MoveStatus.MOVE_OK;
}
return MoveStatus.moveFailed("Expected " + this.transaction
+ "but found " + lastTransaction);
}

setTileIcons

Class: jfreerails.client.renderer.AbstractTileRenderer

Documentation

No documentation available

Source Code

void setTileIcons(Image[] tileIcons) {
this.tileIcons = tileIcons;
}

Called Methods

No outgoing method calls

main

Class: experimental.ExptWriteToBuffer

Documentation

No documentation available

Source Code

public static void main(String[] args) {
try {
Point p = new Point(10, 10);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objectOut = new ObjectOutputStream(out);
objectOut.writeObject(p);
objectOut.flush();
byte[] bytes = out.toByteArray();
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
ObjectInputStream objectIn = new ObjectInputStream(in);
Object o = objectIn.readObject();
Point p2 = (Point) o;
if (p.equals(p2)) {
logger.info("The two objects are equal!");
} else {
logger.info("The two objects are not equal!");
}
} catch (Exception e) {
e.printStackTrace();
}
}

Called Methods

No outgoing method calls

isPackageNameOk

Class: experimental.GenerateDependenciesXmlAndHtml

Documentation

No documentation available

Source Code

static boolean isPackageNameOk(String s) {
return s.matches("(([a-zA-Z]*)/)*\\*")
|| s.matches("(([a-zA-Z]*)/)*\\*\\*/\\*");
}

Called Methods

No outgoing method calls

equals

Class: jfreerails.controller.MessageStatus

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof MessageStatus))
return false;
final MessageStatus messageStatus = (MessageStatus) o;
if (id != messageStatus.id)
return false;
if (successful != messageStatus.successful)
return false;
if (reason != null ? !reason.equals(messageStatus.reason)
: messageStatus.reason != null)
return false;
return true;
}

Called Methods

No outgoing method calls

hasLessThanMaximumNumberOfWagons

Class: jfreerails.world.train.TrainOrdersModel

Documentation

No documentation available

Source Code

public boolean hasLessThanMaximumNumberOfWagons() {
return null == consist || consist.size() < MAXIMUM_NUMBER_OF_WAGONS;
}

removeAllJMenuItemActionPerformed

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void removeAllJMenuItemActionPerformed(
java.awt.event.ActionEvent evt) {// GEN-FIRST:event_removeAllJMenuItemActionPerformed
removeAllWagons();
}// GEN-LAST:event_removeAllJMenuItemActionPerformed

isHit

Class: jfreerails.client.renderer.TrainRenderer

Documentation

No documentation available

Source Code

public boolean isHit(Point mousePosition, TrainModel train, List<Entry<Point, Step>> positions) {
for (int i = 0; i < positions.size(); i++) {
Entry<Point, Step> entry = positions.get(i);
Point p = entry.getKey();
int xDist = mousePosition.x - p.x;
int yDist = mousePosition.y - p.y;
int sumSquares = xDist * xDist + yDist * yDist;
if( sumSquares > 15 * 15){
continue;
}
TrainImages trainImages;
if (i == 0) {
trainImages = rr.getEngineImages(train.getEngineType());
} else {
int type = train.getWagon(i - 1);
trainImages = rr.getWagonImages(type);
}
BufferedImage image = (BufferedImage) trainImages.getOverheadImage(entry.getValue().getID());
int x = xDist + 15;
int y = yDist + 15;
Color c = new Color(image.getRGB(x, y), true);
int alpha = c.getAlpha();
if(alpha > 128){
return true;
}
}
return false;
}

getConsist

Class: jfreerails.world.train.TrainModel

Documentation

No documentation available

Source Code

public ImInts getConsist() {
return wagonTypes;
}

Called Methods

No outgoing method calls

refreshWaitingForFullLoad

Class: jfreerails.controller.TrainStopsHandler

Documentation

No documentation available

Source Code

public boolean refreshWaitingForFullLoad() {
TrainAccessor ta = new TrainAccessor(worldDiffs, principal, trainId);
ImmutableSchedule schedule = ta.getSchedule();
int stationId = ta.getStationId(Double.MAX_VALUE);
if(stationId<0) throw new IllegalStateException();
//The train's orders may have changed...
final int orderToGoto = schedule.getOrderToGoto();
if(-1 == orderToGoto){
//We end up here if all the orders are deleted.
return false;
}
TrainOrdersModel order = schedule.getOrder(orderToGoto);
//Should we go to another station?
if(stationId != order.stationId){
return false;
}
//Should we change the consist?
ImInts consist = ta.getTrain().getConsist();
if(!consist.equals(order.consist)){
// ..if so, we should change the consist.
int oldLength = ta.getTrain().getLength();
int engineType = ta.getTrain().getEngineType();
TrainModel newTrain = ta.getTrain().getNewInstance(engineType, order.consist);
worldDiffs.set(principal, KEY.TRAINS, trainId, newTrain);
int newLength = newTrain.getLength();
//has the trains length increased?
if(newLength > oldLength){
TrainMotion tm = ta.findCurrentMotion(Double.MAX_VALUE);
PathOnTiles path = tm.getPath();
path = lengthenPath(worldDiffs, path, oldLength);
SpeedTimeAndStatus.TrainActivity status = isWaiting4FullLoad() ? WAITING_FOR_FULL_LOAD : STOPPED_AT_STATION;
TrainMotion nextMotion = new TrainMotion(path, newLength,
0, status);
// Create a new Move object.
Move trainMove = new NextActivityMove(nextMotion, trainId,
principal);
MoveStatus ms = trainMove.doMove(worldDiffs, Player.AUTHORITATIVE);
if(!ms.ok) throw new IllegalStateException(ms.message);
}
}
/* Add any cargo that is waiting. */
loadAndUnloadCargo(schedule.getStationToGoto(), order.waitUntilFull, order.autoConsist);
//Should we stop waiting?
if(!order.waitUntilFull){
updateSchedule();
return false;
}
if (isTrainFull()) {
updateSchedule();
return false;
}
return true;
}

tryUndoMove

Class: jfreerails.move.AddItemToListMove

Documentation

No documentation available

Source Code

public MoveStatus tryUndoMove(World w, FreerailsPrincipal p) {
int expectListSize = index + 1;
if (w.size(this.principal, listKey) != expectListSize) {
return MoveStatus.moveFailed("Expected size of "
+ listKey.toString() + " list is " + expectListSize
+ " but actual size is " + w.size(this.principal, listKey));
}
return MoveStatus.MOVE_OK;
}

equals

Class: jfreerails.world.track.NullTrackPiece

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
return o == this;
}

Called Methods

No outgoing method calls

add

Class: jfreerails.world.top.World

Documentation

/**
* Appends the specified element to the end of the specified list and returns
* the index that can be used to retrieve it.
*
*/

Source Code

/**
* Appends the specified element to the end of the specified list and returns
* the index that can be used to retrieve it.
*
*/
int add(SKEY key, FreerailsSerializable element);

Called Methods

No outgoing method calls

getInstance

Class: jfreerails.world.track.FreerailsTile

Documentation

No documentation available

Source Code

public static FreerailsTile getInstance(int terrainType,
TrackPiece trackPiece) {
FreerailsTile tile = new FreerailsTile(terrainType, trackPiece);
if (instances.containsKey(tile)) {
return instances.get(tile);
}
instances.put(tile, tile);
return tile;
}

Called Methods

No outgoing method calls

keepWaiting

Class: jfreerails.controller.TrainAccessor

Documentation

/**
* Returns true iff all the following hold.
* <ol>
* <li>The train is waiting for a full load at some station X.</li>
* <li>The current train order tells the train to goto station X.</li>
* <li>The current train order tells the train to wait for a full load.</li>
* <li>The current train order specifies a consist that matches the train's current consist.</li>
* </ol>
*
*/

Source Code

/**
* Returns true iff all the following hold.
* <ol>
* <li>The train is waiting for a full load at some station X.</li>
* <li>The current train order tells the train to goto station X.</li>
* <li>The current train order tells the train to wait for a full load.</li>
* <li>The current train order specifies a consist that matches the train's current consist.</li>
* </ol>
*
*/
public boolean keepWaiting(){
double time = w.currentTime().getTicks();
int stationId = getStationId(time);
if (stationId == -1)
return false;
SpeedTimeAndStatus.TrainActivity act = getStatus(time);
if (act != TrainActivity.WAITING_FOR_FULL_LOAD)
return false;
ImmutableSchedule schedule = getSchedule();
if(schedule.getNumOrders() <1){
//We end up here if all the train orders are deleted while a train
//is waiting for a full load.
return false;
}
TrainOrdersModel order = schedule.getOrder(schedule.getOrderToGoto());
if (order.stationId != stationId)
return false;
if (!order.waitUntilFull)
return false;
TrainModel train = getTrain();
return order.getConsist().equals(train.getConsist());
}

calcA

Class: jfreerails.world.train.ConstAcc

Documentation

No documentation available

Source Code

public double calcA(double t) {
validateT(t);
return a;
}

getTile

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

public FreerailsSerializable getTile(int x, int y) {
return map[x][y];
}

Called Methods

No outgoing method calls

getStationRadius

Class: jfreerails.client.view.DetailMapRenderer

Documentation

No documentation available

Source Code

public StationRadiusRenderer getStationRadius() {
return stationRadius;
}

Called Methods

No outgoing method calls

getType

Class: jfreerails.server.RandomTerrainValue

Documentation

No documentation available

Source Code

public int getType() {
return terrainType;
}

Called Methods

No outgoing method calls

getStationX

Class: jfreerails.world.station.StationModel

Documentation

No documentation available

Source Code

public int getStationX() {
return x;
}

Called Methods

No outgoing method calls

startNewSegment

Class: jfreerails.world.train.PathWalkerImpl

Documentation

No documentation available

Source Code

private void startNewSegment(IntLine line) {
it.nextSegment(currentSegment);
distanceAlongCurrentSegment = 0;
line.x1 = this.currentSegment.x1;
line.y1 = this.currentSegment.y1;
}

ChequeredTileRenderer

Class: jfreerails.client.renderer.ChequeredTileRenderer

Documentation

No documentation available

Source Code

public ChequeredTileRenderer(ImageManager imageManager, int[] rgbValues,
TerrainType tileModel) throws IOException {
super(tileModel, rgbValues);
this.setTileIcons(new Image[2]);
this.getTileIcons()[0] = imageManager
.getImage(generateRelativeFileName(0));
this.getTileIcons()[1] = imageManager
.getImage(generateRelativeFileName(1));
}

paintRect

Class: jfreerails.client.renderer.BlankMapRenderer

Documentation

No documentation available

Source Code

public void paintRect(Graphics g, Rectangle visibleRect) {
g.setColor(Color.darkGray);
g.fillRect(0, 0, (int) (scale * 400), (int) (scale * 400));
g.setColor(Color.blue);
int x = (int) (100 * scale);
int y = (int) (100 * scale);
int height = (int) (200 * scale);
int width = (int) (200 * scale);
g.fillRect(x, y, height, width);
}

Called Methods

No outgoing method calls

updateSearch

Class: jfreerails.client.renderer.BuildTrackController

Documentation

/**
* Updates the search, if the search is completed, the proposed track is
* shown.
*/

Source Code

/**
* Updates the search, if the search is completed, the proposed track is
* shown.
*/
private void updateSearch() {
try {
if (buildNewTrack) {
path4newTrackFinder.search(100);
} else {
pathOnExistingTrackFinder.search(100);
}
} catch (PathNotFoundException e) {
setCursorMessage(e.getMessage());
return;
}
if (searchStatus() == IncrementalPathFinder.PATH_FOUND) {
if (buildNewTrack) {
builtTrack = path4newTrackFinder.pathAsPoints();
moveCursorMoreTiles(builtTrack);
} else {
boolean okSoFar = true;
path = pathOnExistingTrackFinder.pathAsVectors();
TrackMoveProducer.BuildMode mode = getBuildMode();
int locationX = startPoint.x;
int locationY = startPoint.y;
FreerailsPrincipal fp = modelRoot.getPrincipal();
for (Step v : path) {
Move move;
attemptMove: {
switch (mode) {
case REMOVE_TRACK:
try {
move = ChangeTrackPieceCompositeMove
.generateRemoveTrackMove(new ImPoint(
locationX, locationY), v,
worldDiffs, fp);
break;
} catch (Exception e1) {
e1.printStackTrace();
break attemptMove;
}
case UPGRADE_TRACK:
int owner = ChangeTrackPieceCompositeMove.getOwner(
fp, worldDiffs);
FreerailsTile tile = (FreerailsTile) worldDiffs
.getTile(locationX, locationY);
int tt = tile.getTerrainTypeID();
int trackRuleID = getBts().getRule(tt);
/*
* Skip tiles that already have the right track
* type.
*/
if (trackRuleID == tile.getTrackPiece().getTrackTypeID()) {
break attemptMove;
}
TrackRule trackRule = (TrackRule) worldDiffs.get(
SKEY.TRACK_RULES, trackRuleID);
TrackPiece after = new TrackPieceImpl(tile
.getTrackPiece().getTrackConfiguration(), trackRule, owner,
trackRuleID);
/*
* We don't want to 'upgrade' a station to track.
* See bug 874416.
*/
if (tile.getTrackPiece().getTrackRule().isStation()) {
break attemptMove;
}
move = UpgradeTrackMove.generateMove(tile
.getTrackPiece(), after, new ImPoint(
locationX, locationY));
break;
default:
throw new IllegalStateException(mode.toString());
}// end of switch statement
MoveStatus ms = move.doMove(worldDiffs, fp);
okSoFar = ms.ok && okSoFar;
}// end of attemptMove
locationX += v.deltaX;
locationY += v.deltaY;
}// end for loop
startPoint = new ImPoint(locationX, locationY);
isBuildTrackSuccessful = okSoFar;
if (okSoFar) {
setCursorMessage("");
}
}
show();
}
}

doMove

Class: jfreerails.move.WorldDiffMove

Documentation

No documentation available

Source Code

public MoveStatus doMove(World world, FreerailsPrincipal p) {
MoveStatus ms = tryMapChanges(world, false);
if (!ms.ok)
return ms;
ms = listChanges.doMove(world, p);
if (ms.isOk()) {
doMove(world, false);
}
return ms;
}

StationModel

Class: jfreerails.world.station.StationModel

Documentation

No documentation available

Source Code

public StationModel(StationModel s, Demand4Cargo demand) {
this.demand = demand;
this.cargoBundleNumber = s.cargoBundleNumber;
this.converted = s.converted;
this.name = s.name;
this.production = s.production;
this.supply = s.supply;
this.x = s.x;
this.y = s.y;
}

Called Methods

No outgoing method calls

nextStep

Class: jfreerails.launcher.GUIClient

Documentation

No documentation available

Source Code

public void nextStep(int max) {
// TODO Auto-generated method stub
}

Called Methods

No outgoing method calls

end_TrackType

Class: jfreerails.server.parser.Track_TilesHandler

Documentation

/**
* A container element end event handling method.
*/

Source Code

/**
* A container element end event handling method.
*/
void end_TrackType() throws SAXException;

Called Methods

No outgoing method calls

testTileTypeImpl

Class: jfreerails.world.terrain.MiscTest

Documentation

No documentation available

Source Code

public void testTileTypeImpl() {
Production[] prod = { new Production(69, 10) };
Consumption[] cons = { new Consumption(4, 4), new Consumption(4, 5) };
Conversion[] conv = { new Conversion(50, 30) };
testHashCodeAndEquals(prod[0]);
testHashCodeAndEquals(cons[0]);
testHashCodeAndEquals(conv[0]);
TileTypeImpl tt = new TileTypeImpl(0, Category.Country, "Grassland",
100, prod, cons, conv, 10);
testHashCodeAndEquals(tt);
Conversion[] conv2 = { new Conversion(5, 30) };
TileTypeImpl tt2 = new TileTypeImpl(0, Category.Country, "Grassland",
100, prod, cons, conv2, 10);
assertFalse(tt.equals(tt2));
}

DetailMapRenderer

Class: jfreerails.client.view.DetailMapRenderer

Documentation

No documentation available

Source Code

public DetailMapRenderer(ReadOnlyWorld world, RenderersRoot rr,
ModelRoot modelRoot) {
trainsview = new OverHeadTrainView(world, rr, modelRoot);
MapBackgroundRender render = new MapBackgroundRender(world, rr,
modelRoot);
if (OSXWorkaround) {
// Don't buffer the mapviews background.
background = render;
} else {
background = new SquareTileBackgroundRenderer(render);
}
Dimension mapSize = new Dimension(world.getMapWidth(), world
.getMapHeight());
mapSizeInPixels = new Dimension(mapSize.width * Constants.TILE_SIZE,
mapSize.height * Constants.TILE_SIZE);
stationRadius = new StationRadiusRenderer(modelRoot);
buildTrackRenderer = new BuildTrackRenderer(rr, modelRoot);
buildTrackController = new BuildTrackController(world, modelRoot);
stationBoxes = new StationBoxRenderer(world, rr, modelRoot);
}

equals

Class: jfreerails.world.station.StationModel

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof StationModel))
return false;
final StationModel stationModel = (StationModel) o;
if (cargoBundleNumber != stationModel.cargoBundleNumber)
return false;
if (x != stationModel.x)
return false;
if (y != stationModel.y)
return false;
if (converted != null ? !converted.equals(stationModel.converted)
: stationModel.converted != null)
return false;
if (demand != null ? !demand.equals(stationModel.demand)
: stationModel.demand != null)
return false;
if (!name.equals(stationModel.name))
return false;
if (production != null ? !production.equals(stationModel.production)
: stationModel.production != null)
return false;
if (supply != null ? !supply.equals(stationModel.supply)
: stationModel.supply != null)
return false;
return true;
}

RefreshListOfGamesMessage2Server

Class: jfreerails.network.specifics.RefreshListOfGamesMessage2Server

Documentation

No documentation available

Source Code

public RefreshListOfGamesMessage2Server(final int id) {
super();
this.id = id;
}

Called Methods

No outgoing method calls

isOpen

Class: jfreerails.network.AbstractInetConnection

Documentation

No documentation available

Source Code

public synchronized boolean isOpen() {
return status.isOpen();
}

getTimeStamp

Class: jfreerails.world.accounts.TransactionAndTimeStamp

Documentation

No documentation available

Source Code

public GameTime getTimeStamp() {
return timeStamp;
}

Called Methods

No outgoing method calls

propertyChange

Class: jfreerails.client.view.ServerControlModel

Documentation

No documentation available

Source Code

public void propertyChange(Property p, Object oldValue, Object newValue) {
// switch (p) {
// case SAVED_GAMES_LIST:
// updateLoadGameAction();
// break;
//
// default:
// break;
// }
}

Called Methods

No outgoing method calls

getPlacementRule

Class: jfreerails.world.track.LegalTrackPlacement

Documentation

No documentation available

Source Code

public PlacementRule getPlacementRule() {
return placementRule;
}

Called Methods

No outgoing method calls

getActivity

Class: jfreerails.world.train.SpeedTimeAndStatus

Documentation

No documentation available

Source Code

public TrainActivity getActivity() {
return activity;
}

Called Methods

No outgoing method calls

Money

Class: jfreerails.world.common.Money

Documentation

No documentation available

Source Code

public Money(long amount) {
this.amount = amount;
}

Called Methods

No outgoing method calls

getID

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

No documentation available

Source Code

int getID(FreerailsPrincipal p);

Called Methods

No outgoing method calls

paintComponent

Class: jfreerails.client.view.BrokerScreenHtmlJFrame

Documentation

No documentation available

Source Code

@Override
protected void paintComponent(Graphics g) {
/* Check to see if the text needs updating before painting. */
ReadOnlyWorld world = modelRoot.getWorld();
FreerailsPrincipal playerPrincipal = modelRoot.getPrincipal();
int currentNumberOfTransactions = world
.getNumberOfTransactions(playerPrincipal);
if (currentNumberOfTransactions != lastNumTransactions) {
updateHtml();
}
super.paintComponent(g);
}

TileTypeImpl

Class: jfreerails.world.terrain.TileTypeImpl

Documentation

/**
* Lets unit tests create terrain types without bothering with all the
* details.
*/

Source Code

/**
* Lets unit tests create terrain types without bothering with all the
* details.
*/
public TileTypeImpl(TerrainType.Category terrainCategory, String terrainType) {
this.terrainType = terrainType;
this.terrainCategory = terrainCategory;
this.rgb = 0;
this.rightOfWay = 0;
this.production = new ImList<Production>();
this.consumption = new ImList<Consumption>();
this.conversion = new ImList<Conversion>();
this.tileBuildCost = null;
}

Called Methods

No outgoing method calls

getMapNames

Class: jfreerails.client.view.ServerControlModel

Documentation

/**
* @return an ActionAdapter representing a list of actions representing
* valid map names.
*/

Source Code

/**
* @return an ActionAdapter representing a list of actions representing
* valid map names.
*/
public ActionAdapter getMapNames() {
return selectMapActions;
}

Called Methods

No outgoing method calls

paintTile

Class: jfreerails.client.renderer.TerrainLayer

Documentation

No documentation available

Source Code

public void paintTile(Graphics g, Point tile) {
int screenX = tileSize.width * tile.x;
int screenY = tileSize.height * tile.y;
if ((tile.x >= 0) && (tile.x < mapSize.width) && (tile.y >= 0)
&& (tile.y < mapSize.height)) {
TerrainTile tt = (TerrainTile) w.getTile(tile.x, tile.y);
int typeNumber = tt.getTerrainTypeID();
TileRenderer tr = tiles.getTileViewWithNumber(typeNumber);
if (null == tr) {
logger.warning("No tile renderer for " + typeNumber);
} else {
tr.renderTile(g, screenX, screenY, tile.x, tile.y, w);
}
}
}

initAutomaton

Class: jfreerails.server.ServerAutomaton

Documentation

/**
* Initializes the automaton with a connection to the MoveExecutor.
*/

Source Code

/**
* Initializes the automaton with a connection to the MoveExecutor.
*/
public void initAutomaton(MoveReceiver mr);

Called Methods

No outgoing method calls

setup

Class: jfreerails.client.view.TrainListCellRenderer

Documentation

No documentation available

Source Code

public void setup(ModelRoot mr, RenderersRoot vl, Action closeAction) {
this.w = mr.getWorld();
this.vl = vl;
this.principal = mr.getPrincipal();
}

initCities

Class: jfreerails.server.CityTilePositioner

Documentation

No documentation available

Source Code

void initCities() {
final int numCities = w.size(SKEY.CITIES);
CityEconomicModel[] cities = new CityEconomicModel[numCities];
for (int cityId = 0; cityId < numCities; cityId++) {
CityEconomicModel city = new CityEconomicModel();
city.loadFromMap(w, cityId);
final int urbanTiles = 2 + random.nextInt(3);
for (int i = 0; i < urbanTiles; i++) {
addUrbanTile(city);
}
final int industryTiles = random.nextInt(3);
for (int i = 0; i < industryTiles; i++) {
addIndustryTile(city);
}
final int resourceTiles = random.nextInt(3);
for (int i = 0; i < resourceTiles; i++) {
addResourceTile(city);
}
city.write2map(w);
cities[cityId] = city;
}
}

getProduction

Class: jfreerails.world.station.StationModel

Documentation

No documentation available

Source Code

public ImList<PlannedTrain> getProduction() {
return production;
}

Called Methods

No outgoing method calls

getPasswords

Class: jfreerails.network.specifics.SimpleServerGameModel

Documentation

No documentation available

Source Code

public String[] getPasswords() {
return passwords.clone();
}

Called Methods

  • _Dummy_.__Array__.clone (external)

assertSetupHasBeenCalled

Class: jfreerails.move.AbstractMoveTestCase

Documentation

No documentation available

Source Code

private void assertSetupHasBeenCalled() {
assertTrue("AbstractMoveTestCase.setUp has not been called!",
hasSetupBeenCalled());
}

testProfitsLastYear

Class: jfreerails.controller.StockPriceCalculatorTest

Documentation

No documentation available

Source Code

/*
* Test method for
* 'jfreerails.controller.StockPriceCalculator.profitsLastYear(int)'
*/
public void testProfitsLastYear() {
assertEquals(0, calc.profitsLastYear(0));
int currentTicks = w.currentTime().getTicks();
GameTime newTime = new GameTime(currentTicks + 10);
w.setTime(newTime);
assertEquals(0, calc.profitsLastYear(0));
long income = 100000;
addIncome(income);
assertEquals(0, calc.profitsLastYear(0));
advanceTimeOneYear();
assertEquals(income, calc.profitsLastYear(0));
}

hashCode

Class: jfreerails.move.TimeTickMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
int result;
result = oldTime.hashCode();
result = 29 * result + newTime.hashCode();
return result;
}

setTrackBuilderMode

Class: jfreerails.controller.TrackMoveProducer

Documentation

No documentation available

Source Code

public void setTrackBuilderMode(BuildMode i) {
setBuildMode(i);
}

addD3

Class: jfreerails.util.List3DImpl

Documentation

No documentation available

Source Code

public int addD3(int d1, int d2, T element) {
ArrayList<T> dim3 = elementData.get(d1).get(d2);
dim3.add(element);
return dim3.size()-1;
}

Called Methods

No outgoing method calls

getStatus

Class: jfreerails.controller.SimpleAStarPathFinder

Documentation

No documentation available

Source Code

public int getStatus() {
return status;
}

Called Methods

No outgoing method calls

FreerailsCursor

Class: jfreerails.client.view.FreerailsCursor

Documentation

/**
* Creates a new FreerailsCursor.
*
* @throws IOException
*/

Source Code

/**
* Creates a new FreerailsCursor.
*
* @throws IOException
*/
public FreerailsCursor(ModelRoot mr, RenderersRoot rr) throws IOException {
this.modelRoot = mr;
modelRoot.setProperty(ModelRoot.Property.CURSOR_MESSAGE, null);
buildTrack = rr.getImage("cursor/buildtrack.png");
upgradeTrack = rr.getImage("cursor/upgradetrack.png");
removeTrack = rr.getImage("cursor/removetrack.png");
infoMode = rr.getImage("cursor/infomode.png");
}

isNewGame

Class: jfreerails.launcher.Launcher

Documentation

No documentation available

Source Code

private boolean isNewGame() {
SelectMapJPanel msp2 = (SelectMapJPanel) wizardPages[1];
return msp2.getSelection().equals(SelectMapJPanel.Selection.NEW_GAME);
}

testNextBondInterestRate

Class: jfreerails.controller.FinancialDataGathererTest

Documentation

No documentation available

Source Code

public void testNextBondInterestRate() {
FinancialDataGatherer fdg = new FinancialDataGatherer(w, player
.getPrincipal());
assertEquals(5, fdg.nextBondInterestRate());
w.addTransaction(player.getPrincipal(), BondTransaction.issueBond(5));
fdg = new FinancialDataGatherer(w, player.getPrincipal());
assertEquals(6, fdg.nextBondInterestRate());
}

testLoadFromMap

Class: jfreerails.server.CityEconomicModelTest

Documentation

/**
* Tests generating populated CityEconomicModel from cities on the map.
*/

Source Code

/**
* Tests generating populated CityEconomicModel from cities on the map.
*/
public void testLoadFromMap() {
World w = MapFixtureFactory.getWorld(100, 100);
CityModel newYork = new CityModel("New York", 10, 20);
w.add(SKEY.CITIES, newYork);
CityEconomicModel city = new CityEconomicModel();
city.loadFromMap(w, 0);
assertEquals(0, city.industryTiles.size());
assertEquals(0, city.urbanTiles.size());
assertEquals("A city is a 7*7 area", 49, city.clearTiles.size());
}

testEquals

Class: jfreerails.world.train.ConstAccTest

Documentation

No documentation available

Source Code

public void testEquals() {
SpeedAgainstTime acc1 = ConstAcc.uat(0, 10, 4);
SpeedAgainstTime acc2 = ConstAcc.uat(0, 10, 4);
assertEquals(acc1, acc2);
}

capitalizeEveryWord

Class: jfreerails.util.Utils

Documentation

No documentation available

Source Code

public static String capitalizeEveryWord(String str) {
StringBuffer result = new StringBuffer();
StringTokenizer tok = new StringTokenizer(str);
while (tok.hasMoreTokens()) {
String token = tok.nextToken().toLowerCase();
result.append(Character.toUpperCase(token.charAt(0))
+ token.substring(1) + " ");
}
return result.toString().trim();
}

Called Methods

No outgoing method calls

createHelpMenu

Class: jfreerails.client.top.GUIComponentFactoryImpl

Documentation

No documentation available

Source Code

public JMenu createHelpMenu() {
helpMenu = new javax.swing.JMenu("Help");
JMenuItem about = new JMenuItem("About");
about.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showAbout();
}
});
JMenuItem how2play = new JMenuItem("Getting started");
how2play.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showHow2Play();
}
});
JMenuItem showControls = new JMenuItem("Show game controls");
showControls.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showGameControls();
}
});
JMenuItem showJavaProperties = new JMenuItem("Show Java Properties");
showJavaProperties
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showJavaProperties();
}
});
JMenuItem showReportBug = new JMenuItem("Report Bug");
showReportBug.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dialogueBoxController.showReportBug();
}
});
helpMenu.add(showControls);
helpMenu.add(how2play);
helpMenu.add(showJavaProperties);
helpMenu.add(showReportBug);
helpMenu.add(about);
return helpMenu;
}

sendUpdateMove

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

No documentation available

Source Code

private void sendUpdateMove(MutableSchedule mutableSchedule) {
FreerailsPrincipal principal = modelRoot.getPrincipal();
ReadOnlyWorld w = modelRoot.getWorld();
TrainModel train = (TrainModel) w.get(principal, KEY.TRAINS,
this.trainNumber);
// int scheduleID = train.getScheduleID();
assert (scheduleID == train.getScheduleID());
ImmutableSchedule before = (ImmutableSchedule) w.get(
principal, KEY.TRAIN_SCHEDULES, scheduleID);
ImmutableSchedule after = mutableSchedule.toImmutableSchedule();
Move m = new ChangeTrainScheduleMove(scheduleID, before, after,
principal);
this.modelRoot.doMove(m);
}

incrementFrame

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public void incrementFrame() {
frameCt++;
}

Called Methods

No outgoing method calls

getKey

Class: jfreerails.move.AddItemToSharedListMove

Documentation

No documentation available

Source Code

public SKEY getKey() {
return listKey;
}

Called Methods

No outgoing method calls

nextEdge

Class: jfreerails.controller.Map

Documentation

No documentation available

Source Code

public void nextEdge() {
if (hasNextEdge()) {
branch++;
} else {
throw new NoSuchElementException();
}
}

getTileViewWithNumber

Class: jfreerails.client.renderer.TileRendererListImpl

Documentation

No documentation available

Source Code

public TileRenderer getTileViewWithNumber(int i) {
return tiles[i];
}

Called Methods

No outgoing method calls

addD1

Class: jfreerails.util.List3DImpl

Documentation

No documentation available

Source Code

public int addD1() {
ArrayList<ArrayList<T>> dim2 = new ArrayList<ArrayList<T>>();
elementData.add(dim2);
return elementData.size() -1;
}

Called Methods

No outgoing method calls

setVisible

Class: jfreerails.client.renderer.BuildTrackController

Documentation

No documentation available

Source Code

private void setVisible(boolean show) {
if (show == visible) {
return;
}
if (show) {
setWorldDiffs(worldDiffs);
} else {
setWorldDiffs(null);
}
this.visible = show;
}

setCrashSite

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public void setCrashSite(boolean isCrash) {
crashSite = isCrash;
}

Called Methods

No outgoing method calls

getNewMapNames

Class: jfreerails.network.specifics.SavedGamesManager4UnitTests

Documentation

No documentation available

Source Code

public String[] getNewMapNames() {
return mapsAvailable.clone();
}

Called Methods

  • _Dummy_.__Array__.clone (external)

equals

Class: jfreerails.util.Lists

Documentation

No documentation available

Source Code

@SuppressWarnings("unchecked")
public static boolean equals(List3D a, List3D b) {
if (a.sizeD1() != b.sizeD1())
return false;
for (int d1 = 0; d1 < a.sizeD1(); d1++) {
if (a.sizeD2(d1) != b.sizeD2(d1))
return false;
for (int d2 = 0; d2 < a.sizeD2(d1); d2++) {
if (a.sizeD3(d1, d2) != b.sizeD3(d1, d2))
return false;
for (int d3 = 0; d3 < a.sizeD3(d1, d2); d3++) {
if (!Utils.equal(a.get(d1, d2, d3), b.get(d1, d2, d3)))
return false;
}
}
}
return true;
}

equals

Class: jfreerails.world.top.WorldImpl

Documentation

No documentation available

Source Code

@Override
public boolean equals(Object o) {
if (o instanceof WorldImpl) {
WorldImpl test = (WorldImpl) o;
// Compare players
int numberOfPlayers = getNumberOfPlayers();
if (numberOfPlayers != test.getNumberOfPlayers())
return false;
for (int i = 0; i < numberOfPlayers; i++) {
if (!getPlayer(i).equals(test.getPlayer(i)))
return false;
}
// Compare lists
if (!lists.equals(test.lists)) {
return false;
}
if (!sharedLists.equals(test.sharedLists)) {
return false;
}
if (!activityLists.equals(test.activityLists)) {
return false;
}
if (!items.equals(test.items)) {
return false;
}
if (!bankAccounts.equals(test.bankAccounts)) {
return false;
}
// Compare maps
if ((this.getMapWidth() != test.getMapWidth())
|| (this.getMapHeight() != test.getMapHeight())) {
return false;
}
for (int x = 0; x < this.getMapWidth(); x++) {
for (int y = 0; y < this.getMapHeight(); y++) {
if (!getTile(x, y).equals(test.getTile(x, y))) {
return false;
}
}
}
// phew!
return true;
}
return false;
}

getConversion

Class: jfreerails.world.station.ConvertedAtStation

Documentation

No documentation available

Source Code

public int getConversion(int cargoNumber) {
return convertedTo.get(cargoNumber);
}

generateRemoveTrackMove

Class: jfreerails.move.ChangeTrackPieceCompositeMove

Documentation

No documentation available

Source Code

public static ChangeTrackPieceCompositeMove generateRemoveTrackMove(
ImPoint from, Step direction, ReadOnlyWorld w,
FreerailsPrincipal principal) throws Exception {
TrackMove a;
TrackMove b;
a = getRemoveTrackChangeTrackPieceMove(from, direction, w, principal);
b = getRemoveTrackChangeTrackPieceMove(direction
.createRelocatedPoint(from), direction.getOpposite(), w,
principal);
return new ChangeTrackPieceCompositeMove(a, b, principal);
}

getAfter

Class: jfreerails.move.AddItemToListMove

Documentation

No documentation available

Source Code

public FreerailsSerializable getAfter() {
return item;
}

Called Methods

No outgoing method calls

hashCode

Class: jfreerails.move.UndoMove

Documentation

No documentation available

Source Code

@Override
public int hashCode() {
return move2undo.hashCode();
}

Called Methods

No outgoing method calls

showStationInfo

Class: jfreerails.client.view.DialogueBoxController

Documentation

No documentation available

Source Code

public void showStationInfo(int stationNumber) {
try {
stationInfo.setStation(stationNumber);
showContent(stationInfo);
} catch (NoSuchElementException e) {
logger.warning("Station " + stationNumber + " does not exist!");
}
}

condition

Class: jfreerails.world.top.ItemsTransactionAggregator

Documentation

/**
* Returns true if the transaction with the specified ID has an acceptable
* type and category.
*/

Source Code

/**
* Returns true if the transaction with the specified ID has an acceptable
* type and category.
*/
@Override
protected boolean condition(int transactionID) {
Transaction t = w.getTransaction(principal, transactionID);
if (!(t instanceof AddItemTransaction)) {
return false;
}
AddItemTransaction addItemTransaction = (AddItemTransaction) t;
boolean isTypeAcceptable = (type == ANY_VALUE)
|| (type == addItemTransaction.getType());
boolean isCategoryAcceptable = (category == null)
|| (category == addItemTransaction.getCategory());
return isCategoryAcceptable && isTypeAcceptable;
}

getTrackMoveProducer

Class: jfreerails.client.view.ActionRoot

Documentation

No documentation available

Source Code

public TrackMoveProducer getTrackMoveProducer() {
return trackMoveProducer;
}

Called Methods

No outgoing method calls

setUp

Class: jfreerails.controller.MoveTrainPreMove2ndTest

Documentation

No documentation available

Source Code

@Override
/** <ol>
* <li>Obtains a map from MapFixtureFactory2</li>
* <li>Builds a track from (10,10) to (30, 10).</li>
* <li>Builds stations at (10,10), (20, 10), and (28,10).</li>
* <li>Builds a train with two wagons of type #0 and places it at (10, 10)</li>
* <li>Schedules the train to move between stations 0 and 2 without changing consist</li>
* </ol>
*/
protected void setUp() throws Exception {
world = MapFixtureFactory2.getCopy();
MoveExecutor me = new SimpleMoveExecutor(world, 0);
principal = me.getPrincipal();
ModelRoot mr = new ModelRootImpl();
trackBuilder = new TrackMoveProducer(me, world, mr);
stationBuilder = new StationBuilder(me);
// Build track.
stationBuilder.setStationType(stationBuilder.getTrackTypeID("terminal"));
Step[] track = new Step[20];
for (int i = 0; i < track.length; i++) {
track[i] = EAST;
}
station0Location = new ImPoint(10, 10);
MoveStatus ms0 = trackBuilder.buildTrack(station0Location, track);
assertTrue(ms0.ok);
// Build 2 stations.
MoveStatus ms1 = stationBuilder.buildStation(station0Location);
assertTrue(ms1.ok);
station1Location = new ImPoint(20, 10);
MoveStatus ms2 = stationBuilder.buildStation(station1Location);
assertTrue(ms2.ok);
station2Location = new ImPoint(28, 10);
MoveStatus ms3 = stationBuilder.buildStation(station2Location);
assertTrue(ms3.ok);
TrainOrdersModel order0 = new TrainOrdersModel(2, null, false, false);
TrainOrdersModel order1 = new TrainOrdersModel(0, null, false, false);
MutableSchedule s = new MutableSchedule();
s.addOrder(order0);
s.addOrder(order1);
defaultSchedule = s.toImmutableSchedule();
ImPoint start = new ImPoint(10, 10);
AddTrainPreMove preMove = new AddTrainPreMove(0, new ImInts(0, 0), start, principal,
defaultSchedule);
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, principal);
assertTrue(ms.ok);
}

showSelectStation

Class: jfreerails.client.view.TrainScheduleJPanel

Documentation

/**
* Show the popup that lets the user select a station, called when a new
* scheduled stop is added and when an existing scheduled stop is changed.
*/

Source Code

/**
* Show the popup that lets the user select a station, called when a new
* scheduled stop is added and when an existing scheduled stop is changed.
*/
private void showSelectStation(MutableSchedule schedule, int orderNumber) {
selectStationJPanel1.display(schedule, orderNumber);
// Show the select station popup in the middle of the window.
Container topLevelAncestor = this.getTopLevelAncestor();
Dimension d = topLevelAncestor.getSize();
Dimension d2 = selectStationJPopupMenu.getPreferredSize();
int x = Math.max((d.width - d2.width) / 2, 0);
int y = Math.max((d.height - d2.height) / 2, 0);
selectStationJPopupMenu.show(topLevelAncestor, x, y);
selectStationJPanel1.requestFocus();
}

moveTrain

Class: jfreerails.controller.MoveTrainPreMove2ndTest

Documentation

No documentation available

Source Code

private TrainMotion moveTrain() {
incrTime(world, principal);
MoveTrainPreMove preMove = new MoveTrainPreMove(0, principal);
Move m = preMove.generateMove(world);
MoveStatus ms = m.doMove(world, principal);
assertTrue(ms.message, ms.ok);
TrainAccessor ta = new TrainAccessor(world, principal, 0);
TrainMotion tm = ta.findCurrentMotion(Integer.MAX_VALUE);
return tm;
}

get

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

/**
* Returns the element at the specified position in the specified list.
*/

Source Code

/**
* Returns the element at the specified position in the specified list.
*/
FreerailsSerializable get(SKEY key, int index);

Called Methods

No outgoing method calls

calcS

Class: jfreerails.world.train.CompositeSpeedAgainstTime

Documentation

No documentation available

Source Code

public double calcS(double t) {
if(t == this.finalT) return this.finalS;
checkT(t);
TandI tai = getIndex(t);
double s = 0;
for (int i = 0; i < tai.i; i++) {
SpeedAgainstTime acc = values.get(i);
s += acc.getS();
}
SpeedAgainstTime acc = values.get(tai.i);
if(tai.offset >= acc.getT()){
//Note, it is possible for tai.offset > acc.getT()
//even though we called checkT(t) above
s += acc.getS();
}else{
s += acc.calcS(tai.offset);
}
return s;
}

setTile

Class: jfreerails.world.top.WorldDiffs

Documentation

No documentation available

Source Code

@Override
public void setTile(int x, int y, FreerailsSerializable tile) {
ImPoint p = new ImPoint(x, y);
if (Utils.equal(underlying.getTile(x, y), tile)) {
if (this.mapDiff.containsKey(p)) {
this.mapDiff.remove(p);
return;
}
} else {
this.mapDiff.put(p, tile);
}
}

testLogon

Class: jfreerails.network.specifics.FreerailsClientWithLocalServerTest

Documentation

/** Copy & pasted from FreerailsClientTest, then edited. */

Source Code

/** Copy & pasted from FreerailsClientTest, then edited. */
public void testLogon() {
try {
/* Test 1 : connecting a client. */
assertEquals("No client connected yet.", 0, server
.countOpenConnections());
FreerailsClient client = new FreerailsClient();
LogOnResponse response = client.connect(server, "name", "password");
assertTrue(response.isSuccessful());
assertEquals(1, server.countOpenConnections());
// Check the client gets its properties updated.
client.update();
assertNotNull(client
.getProperty(ClientControlInterface.ClientProperty.CONNECTED_CLIENTS));
assertNotNull(client
.getProperty(ClientControlInterface.ClientProperty.MAPS_AVAILABLE));
assertNotNull(client
.getProperty(ClientControlInterface.ClientProperty.SAVED_GAMES));
/* Test 2 : a client that has already logged on. */
FreerailsClient client1 = new FreerailsClient();
response = client1.connect(server, "name", "password");
assertFalse("The player is already logged on.", response
.isSuccessful());
assertEquals(1, server.countOpenConnections());
/* Test 3 : connecting a client. */
FreerailsClient client3 = new FreerailsClient();
response = client3.connect(server, "name3", "password");
assertTrue(response.isSuccessful());
assertEquals(2, server.countOpenConnections());
/* Test 4 : disconnect the client from test 1. */
client.disconnect();
assertEquals(1, server.countOpenConnections());
} catch (Exception e) {
e.printStackTrace();
fail();
}
}

boundsContain

Class: jfreerails.world.top.ReadOnlyWorld

Documentation

No documentation available

Source Code

boolean boundsContain(SKEY k, int index);

Called Methods

No outgoing method calls

getOwnerID

Class: jfreerails.world.track.TrackPiece

Documentation

No documentation available

Source Code

int getOwnerID();

Called Methods

No outgoing method calls

getAcceleration

Class: jfreerails.world.train.TrainPositionOnMap

Documentation

No documentation available

Source Code

public double getAcceleration() {
return acceleration;
}

Called Methods

No outgoing method calls

ImPoint

Class: jfreerails.world.common.ImPoint

Documentation

No documentation available

Source Code

public ImPoint() {
x = 0;
y = 0;
}

Called Methods

No outgoing method calls

dumpImages

Class: jfreerails.client.renderer.RiverStyleTileRenderer

Documentation

No documentation available

Source Code

@Override
public void dumpImages(ImageManager imageManager) {
for (int i = 0; i < this.getTileIcons().length; i++) {
imageManager.setImage(generateRelativeFileName(i), this
.getTileIcons()[i]);
}
}

TrackConfigurationTest

Class: jfreerails.world.track.TrackConfigurationTest

Documentation

No documentation available

Source Code

public TrackConfigurationTest(java.lang.String testName) {
super(testName);
}

Called Methods

No outgoing method calls

finished

Class: jfreerails.launcher.ProgressJPanel

Documentation

No documentation available

Source Code

public void finished() {
if(numSteps-1 != step)
throw new IllegalStateException(numSteps +"!="+ step);
getTopLevelAncestor().setVisible(false);
}

Called Methods

No outgoing method calls

undoMove

Class: jfreerails.move.NextActivityMove

Documentation

No documentation available

Source Code

public MoveStatus undoMove(World w, FreerailsPrincipal p) {
MoveStatus ms = tryUndoMove(w, p);
if (ms.ok)
w.removeLastActivity(principal, index);
return ms;
}

getCb

Class: jfreerails.world.accounts.DeliverCargoReceipt

Documentation

No documentation available

Source Code

public CargoBatch getCb() {
return cb;
}

Called Methods

No outgoing method calls

storeRunningTotal

Class: jfreerails.world.top.ItemsTransactionAggregator

Documentation

No documentation available

Source Code

@Override
protected void storeRunningTotal(int timeIndex) {
/*
* Note, a negative sign since we are totalling the value of assets not
* their impact on the operating funds.
*/
monetaryTotals[timeIndex] = new Money(-runningTotal);
quantities[timeIndex] = quantityRunningTotal;
}

Called Methods

No outgoing method calls

confirmExitActionPerformed

Class: jfreerails.client.view.ConfirmExitJPanel

Documentation

No documentation available

Source Code

private void confirmExitActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_confirmExitActionPerformed
System.exit(0);
}// GEN-LAST:event_confirmExitActionPerformed

Called Methods

No outgoing method calls

testContract

Class: jfreerails.world.train.CompositeSpeedAgainstTimeTest

Documentation

No documentation available

Source Code

public void testContract(){
Random r = new Random(123);
for(int i = 0 ; i < 1000; i++){
int numberOfParts = r.nextInt(10) + 1;
SpeedAgainstTime[] parts = new SpeedAgainstTime[numberOfParts];
for(int j = 0; j < numberOfParts; j++){
parts[j] = ConstAcc.uat(r.nextDouble(), r.nextDouble(), r.nextDouble());
}
CompositeSpeedAgainstTime csat = new CompositeSpeedAgainstTime(parts);
ConstAccTest.checkContract(csat);
}
}

createBrokerMenu

Class: jfreerails.client.top.GUIComponentFactoryTestImpl

Documentation

No documentation available

Source Code

public JMenu createBrokerMenu() {
return brokerMenu;
}

Called Methods

No outgoing method calls